Basic authentication middleware for ASP.NET 5

July 23, 2015 by Anuraj

.Net ASP.Net ASP.Net MVC Visual Studio Web API

This post is about building another middleware component for ASP.NET 5. Long back I wrote a post about Basic authentication for Web API. This implementation uses the same functionality. It checks for Authorization header in the HTTP Request, if not found it set the Response status code to 401 and adds a WWW-Authenticate header. When browser receives such response, it will show the Basic authentication dialog. If the header is set, you can parse the header and validate the credentials against database. Here is the implementation.

public async Task Invoke(HttpContext context)
    var authHeader = context.Request.Headers.Get("Authorization");
    if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
        var token = authHeader.Substring("Basic ".Length).Trim();
        var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
        var credentials = credentialstring.Split(':');
        if(credentials[0] == "admin" && credentials[1] == "admin")
            var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
            var identity = new ClaimsIdentity(claims, "Basic");
            context.User = new ClaimsPrincipal(identity);
        context.Response.StatusCode = 401;
        context.Response.Headers.Set("WWW-Authenticate", "Basic realm=\"\"");
    await _next(context);

And here is the code running on HTTP listener.

Basic HTTP authentication dialog

Happy Programming :)

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub