Blog

Filter posts by Category Or Tag of the Blog section!

Middleware for basic authentication

Friday, 07 September 2018

There are different kinds of authentication. One of the most used ones is basic authentication that doesn’t expire like a bearer token and you need to send a username and password per each request. In order to handle such an authentication you can middleware:


   

public class AuthenticationMiddleware

    {

        private readonly RequestDelegate _next;



        public AuthenticationMiddleware(RequestDelegate next)

        {

            _next = next;

        }



        public async Task Invoke(HttpContext context)

        {

            string authHeader = context.Request.Headers["Authorization"];

       

            if (authHeader != null && authHeader.StartsWith("Basic"))

            {

                //Extract credentials

                string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();

                Encoding encoding = Encoding.GetEncoding("iso-8859-1");

                string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));



                int seperatorIndex = usernamePassword.IndexOf(':');



                var username = usernamePassword.Substring(0, seperatorIndex);

                var password = usernamePassword.Substring(seperatorIndex + 1);



                //fetch user/pass from Db 

                if( username == "MyUser" && password == "MyPass")

                 {

                     await _next.Invoke(context);

                 }

                else

                {

                    context.Response.StatusCode = 401; //Unauthorized

                    return;

                }

            }

        }

    }

 

A simple middleware that handles every incoming request and verifies the username and password. Notice that, fetching usernames and passwords for every request could be really cost-effective, and based on the usage you should create it wisely. By registering the above middleware in Configure() of Startup class: 

 

app.UseMiddleware<AuthenticationMiddleware>();
app.UseMvc();



You can use the middle. By doing this you don’t even need to use Authorize attribute in your controllers.

comments powered by Disqus