Custom authentication middleware in dotnet core

Author : Sachin Sharma
Published On : 10 Apr 2023

Middleware is a class that is execute on every request. we can set the order of middleware execution in the request pipeline. each middleware adds or modifies http request and optionally passes control to the next middleware component.

we can configure middleware in configure method of startup.cs class.

Here we will discuss about custom authentication middleware and how to configure custom authentication middleware in dotnet core.

 public class CustomAuthMiddleware
    {
        private readonly RequestDelegate _next;
        public CustomAuthMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
                var endpoint = context.GetEndpoint();
                if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() is object)
                {
                    await _next(context);
                    return;
                }

                var token = context.Request.Cookies["AuthUser"];

                if (token != null)
                {
                    (bool isValidToken, CurrentUserData user) = Security.ValidateToken(token);
                    if (isValidToken)
                    {
                        context.Items["CurrentUser"] = user;
                        await _next(context);
                        return;
                    }
                    else
                    {
                        context.Response.Redirect("/user/login");
                        return;
                    }
                }
                else
                {
                    context.Response.Redirect("/user/login");
                    return;
                }                      
        }
    }

now execute CustomAuthMiddleware class in configure method of statup.cs 

 app.UseMiddleware<CustomAuthMiddleware>();

Startup.cs 

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

            app.UseRouting();

            app.UseAuthorization();

            app.UseMiddleware<CustomAuthMiddleware>();           

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=User}/{action=Login}/{id?}");
            });
        }

this is the way to create a middleware in dotnet core mvc.

Comments

No comments have been added to this article.

Add Comment