DEV Community

Nagasudhir Pulla
Nagasudhir Pulla

Posted on

Cookie based authentication & authorization in ASP.NET Core explained

Video - https://youtu.be/GhZLi8pBJow?si=mnIVpCke9OJBMFoJ

Services for Authentication and Authorization

Authentication Service

  • Maintains multiple authentication schemes
  • Uses Cookie handler to Build ClaimsPrincipal from cookie, set up request redirection for login, logout, access denial
  • Add cookie authentication service in DI container using the following
// 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
    });

Enter fullscreen mode Exit fullscreen mode
  • AddAuthentication adds the authentication service to DI container. It also specifies the default authentication scheme (Cookies) for authentication.
  • AddCookie provides a cookie authentication handler for the Cookies authentication scheme.

Authorization Service

  • Evaluates ClaimsPrincipal's claims against authorization policies to determine if the request is authorized
  • Add authorization service in DI container using the following
builder.Services.AddAuthorization(options =>
{
    // Define a rule named "AdminOnly"
    options.AddPolicy("AdminOnly", policy => 
        policy.RequireRole("Admin")
              .RequireClaim("EmployeeId"));
});
Enter fullscreen mode Exit fullscreen mode
  • The above code adds a policy named AdminOnly along with default available authorization service policies

A Request's Journey for cookie-based Authentication and Authorization in dotnet

auth middleware arch

Phase 1 - Authentication middleware (for Identification)

  • Authentication middleware identifies the visitor by extracting the ClaimsPrincipal from cookie and attaches it to HttpContext
  • Authenticaiton middleware is added to the request pipeline using the following
app.UseAuthentication();
Enter fullscreen mode Exit fullscreen mode

Steps

  • Middleware asks the Authentication Service (configured via AddAuthentication) for a ClaimsPrincipal (user).
  • Authentication Service calls the Cookie Handler. It decrypts the cookie (using Data Protection Provider) and creates a ClaimsPrincipal
  • The created ClaimsPrincipal is attached to HttpContext.User. The request moves to the next middleware.

Phase 2: Authorization middleware (for Permissions check)

  • Authorization middleware evaluates the identified ClaimsPrincipal's claims and redirects the request to login or denies the request if claims don't meet the authorization requirements
  • Authorization middleware is added to the request pipeline using the following
app.UseAuthorization();
Enter fullscreen mode Exit fullscreen mode

Steps

  • Authorization middleware checks the endpoint for attributes like [Authorize] or a specific policy (e.g., [Authorize(Policy = "AdminOnly")]).
  • Authorization middleware asks the Authorization Service (registered via AddAuthorization) to evaluate the ClaimsPrincipal's claims against those rules.
  • Based on that evaluation, the system executes one of three paths:
Path A: User is Not Logged In (Challenge the request)
  • Condition: The authorization policy requires a user, but HttpContext.User is anonymous.
  • Action: The Authorization middleware triggers a Challenge by calling the ChallengeAsync method on the Authentication service.
  • Execution: Authentication service delegates the Challenge execution to Cookie Handler, which modifies HttpContext.Response for a 302 Redirect to LoginPath. The pipeline short-circuits.
Path B: User has Wrong Permissions (Forbid the request)
  • Condition: ClaimPrincipal is present, but the claims fail the requirements of authorization policies.
  • Action: The Authorization middleware triggers a Forbid by calling the ForbidAsync method on the Authentication service.
  • Execution: Authentication service delegates the Forbid execution to Cookie Handler, which modifies HttpContext.Response for a 302 Redirect to AccessDeniedPath. The pipeline short-circuits.
Path C: Access Granted
  • Condition: The user's claims satisfy all requirements in the Authorization Service.
  • Execution: The middleware calls next(), allowing the request to reach next middleware (like controllers).

Setting logged in user in the cookie

  • The user will submit credentials in the login page
  • The user credentials will be verified from a database and ClaimsPrincipal will be created to represent the logged in user
  • HttpContext.SignInAsync uses Authentication service's Cookie Handler to set the logged in user details (a ClaimsPrincipal) in the response cookie
await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    authProperties);

Enter fullscreen mode Exit fullscreen mode

Signout logged in user

await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

Enter fullscreen mode Exit fullscreen mode
  • HttpContext.SignOutAsync uses Authentication service's Cookie Handler to expire the cookie that contains the logged in user details (a ClaimsPrincipal) and makes the HttpContext.User as anonymous

Access the ClaimsPrincipal (logged in user)

  • After the authentication middleware derives a valid ClaimsPrincipal from the cookie, it sets the user details (ClaimsPrincipal) in the HttpContext.User object
  • Hence
    • 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

Top comments (0)