Cookie based authentication explained in ASP.NET Core

cookie_auth

Cookie based authentication explained in ASP.NET Core

Cookie based authentication can be implemented in ASP.NET Core using the built in Authentication service and Authentication middleware

// Add Cookie Authentication service
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Account/Login"; // Specify the path to the login page
        options.AccessDeniedPath = "/Account/AccessDenied"; // Specify the path for access denied
        options.ExpireTimeSpan = TimeSpan.FromMinutes(60); // Set the cookie expiration time
        options.SlidingExpiration = true; // Enable sliding expiration
    });

  • AddAuthentication adds required services for authentication. It also specifies the default authentication scheme to be used for authentication. In this example, the default scheme is CookieAuthenticationDefaults.AuthenticationScheme
  • AddCookie provides an authentication handler (that uses cookies) for the authentication scheme.
  • Authenticaiton middleware is added to the request pipeline using the following
app.UseAuthentication();

auth middleware arch

  • The middleware uses the DI container’s authentication service to determine the logged in user details from the request cookie and populates the User’s ClaimsPrincipal in HttpContext.User
  • Now the subsequent middleware (like razor pages, controllers etc) can figure out the logged in user details to grant or revoke access

  • User will submit credentials and complete required challenges like 2 factor authentication in the login page
  • The user credentials will be verified from a database a ClaimsPrincipal will be created to represent the logged in user
  • HttpContext.SignInAsync sets the logged in user details (in the form of a ClaimsPrincipal) in the cookie
await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    authProperties);

Signout logged in user

await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

  • HttpContext.SignOutAsync expires the cookie that contains the logged in user details (ClaimsPrincipal) and makes the HttpContext.User as null

Access logged in user details

  • After the authentication middleware figures out the logged in user details from the cookie, the user details (ClaimsPrincipal) can be accessed via HttpContext.User object
  • For example
    • HttpContext.User?.Identity?.IsAuthenticated can be used to determine if a request is authenticated
    • HttpContext.User.Identity.Name can be used to determine the logged in user name

References

Comments

Popular posts from this blog

ClaimsPrincipal, ClaimsIdentity, Claims explained in dotnet authentication

Manage packages in dotnet applications