skip to Main Content

I’m wondering what component verifies a incoming authentication-cookie and sets HttpContext.User.Identity.IsAuthenticated to true even before the very first middleware component is executed, even when I do not have app.UseAuthentication()in the middleware pipeline at all.

So far, I expected this authentication middleware component to do that job. I’ve created a custom middleware module, added it in the first place of the middleware pipeline and when this module is called, IsAuthenticated is already true – as long as a valid cookie comes in from the browser. Can someone please explain who or what evaluates the cookie and sets IsAuthenticated to true?

I have a simple login page to enter name/password that end up in the following Post-handler – and no, that is no production code! 🙂

public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid) 
        return Page();

    if (Credential is { UserName: "admin", Password: "password" })
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, "admin"),
            new Claim(ClaimTypes.Email, "[email protected]")
        };

        var identity = new ClaimsIdentity(claims, "MyCookieAuth");
        var claimsPrincipal = new ClaimsPrincipal(identity);

        await HttpContext.SignInAsync("MyCookieAuth", claimsPrincipal);

        return Redirect("/index");
    }

    return Page();
}

This is the program.cs:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddAuthentication().AddCookie("MyCookieAuth", options =>
{
    options.Cookie.Name = "MyCookieAuth";
    
});

var app = builder.Build();

app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
app.Run();

And a simple index.cshtml to show the status of IsAuthenticated:

@page
@model IndexModel

<div class="text-center">
    <p>IsAuthenticated: @HttpContext.User.Identity.IsAuthenticated</p>
</div>

When I log in successfully, a cookie is sent back to the browser, I get redirected to the index page and I’m authenticated and everything is fine and understandable.

But if I come back with that cookie, directly to the index page, I’m immediately authenticated. And as you can see, I do NOT have app.UseAuthentication(); in the pipeline. How?

2

Answers


  1. This is happening because Authentication Handler is automatically registered by ASP.Net Core.
    Normally we Add app.UseAuthentication() in our middleware,
    Even though you haven’t added it that got automatically registered because of AddAuthentication() code in your Program.cs and this will set the Authentication of HttpContext.User.

    builder.Services.AddAuthentication().AddCookie("MyCookieAuth", options =>
    {
        options.Cookie.Name = "MyCookieAuth";
        
    });
    

    Cookie Authentication handler will inspect the requests for the authentication cookie, and if it finds valid cookie it will authenticate the user and set HttpContext.User.IsAuthenticated to True.

    Login or Signup to reply.
  2. The behavior you’re observing is due to the way ASP.NET Core handles authentication cookies and user identity. Even though you don’t have app.UseAuthentication() in your middleware pipeline, the authentication process still takes place. In an usual setup, the app.UseAuthentication() middleware is responsible for validating authentication tokens (such as cookies) and setting the HttpContext.User property.
    But… when you configure the authentication scheme using builder.Services.AddAuthentication().AddCookie("MyCookieAuth", …), you are setting up the default authentication scheme for the application. This includes defining the cookie name and other settings.
    ASP.NET Core’s request handling process includes several built-in services that execute even before the middleware pipeline is invoked. One of those services is responsible for automatic authentication. This service inspects incoming requests for authentication tokens (cookies, headers, etc.) and automatically validates them. If a valid token is found, the service sets the HttpContext.User property, which includes setting HttpContext.User.Identity.IsAuthenticated to true.

    So, in your code what’s happening is:

    –  When the request with the authentication cookie hits your application, the built-in authentication handler reads and validates the cookie.

    • If the cookie is valid, the handler creates a ClaimsPrincipal based on the claims stored in the cookie and assigns it to HttpContext.User.
    • This process occurs before any middleware (including your custom middleware) is executed.

    Even without app.UseAuthentication(), the authentication handler is still triggered because you have configured authentication in the AddAuthentication method.
    By the time your custom middleware runs, HttpContext.User is already populated with the authenticated user’s information, which can be frustrating if it’s not what you want.
    Even though your application works without explicitly adding app.UseAuthentication(), it might be a good practice to include it in your middleware pipeline to make the authentication process explicit.

    Here’s how you can do it:

    app.UseStaticFiles();
    app.UseRouting();
    
    // Add UseAuthentication before UseAuthorization
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.MapRazorPages();
    app.Run();
    

    By adding app.UseAuthentication(), you make the authentication process to be explicitly part of your middleware pipeline, making it clearer to anyone reading the code where and when authentication occurs.

    Hope this helps!

    BTW… you can check this page for more info on Auth methods 🙂

    https://learn.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-8.0

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search