1 year ago

#385262

test-img

melspring

How to redirect to custom 403 using Middleware - asp.net

I'm trying to redirect if authentication fails to a custom 403 page which Is not working. The web pages should only be accessible if the user is authenticated via LDAP(should belong to a particular group)

this is what i've done so far:

  1. Added Authorization middleware
  2. Added Authorization middleware extension
  3. Configure it in startup.cs
  4. Added Error controller and Views
        public async Task Invoke(HttpContext context)
        {

            // create and search ldap
            DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapServer);
            DirectorySearcher mySearcher = new DirectorySearcher(entry);
            var userName = context.User.Identity.Name;
            userName = System.IO.Path.GetFileNameWithoutExtension(userName);
            // look for SAM account names in groups for the user
            mySearcher.Filter = "(&(objectClass=user)(|(cn=" + userName + ")(sAMAccountName=" + userName + ")))";
            SearchResult result = mySearcher.FindOne();
            var isAuthorized = false;
            foreach (string GroupPath in result.Properties["memberOf"])
            {
                if (GroupPath.Contains(AuthorisedGroup))
                {
                    isAuthorized = true;
                }
            }


            // Return error if the current user is not authorized
            if (!isAuthorized)
            {

                context.Response.StatusCode = 403;
                return;
            }
            // Jump to the next middleware if the user is authorized
             await NextRequest.Invoke(context);
       }

Configure method in startup.cs

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseStatusCodePagesWithReExecute("/Error/{0}");
                //app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseStatusCodePagesWithReExecute("/Error/{0}");
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAdAuthorizationMiddleware();//<------- Middleware config

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Fault}/{action=Fault}/{id?}");
            });
        }

Error Controller

    public class ErrorController : Controller
    {

        [Route("Error/{statusCode}")]
        public IActionResult StatusCodeHandler(string statusCode)
        {
            return View($"{statusCode}");
        }
    }

I've added 2 views

enter image description here

if I type an invalid url it does show custom 404, but if i set isAuthorized = false it doesn't get to the controller hence shows the standard 403 page instead of custom page.

Thanks for any help

c#

razor

asp.net-mvc-5

http-error

custom-errors

0 Answers

Your Answer

Accepted video resources