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
});
-
AddAuthenticationadds the authentication service to DI container. It also specifies the default authentication scheme (Cookies) for authentication. -
AddCookieprovides 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"));
});
- The above code adds a policy named
AdminOnlyalong with default available authorization service policies
A Request's Journey for cookie-based Authentication and Authorization in dotnet
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();
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();
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.SignInAsyncuses 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);
Signout logged in user
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
-
HttpContext.SignOutAsyncuses Authentication service's Cookie Handler to expire the cookie that contains the logged in user details (a ClaimsPrincipal) and makes theHttpContext.Useras 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.Userobject - Hence
-
HttpContext.User?.Identity?.IsAuthenticatedcan be used to determine if a request is authenticated -
HttpContext.User.Identity.Namecan be used to determine the logged in user name
-



Top comments (0)