{"id":2819,"date":"2026-05-10T14:21:24","date_gmt":"2026-05-10T07:21:24","guid":{"rendered":"https:\/\/daiilynews.cu.ma\/cookie-based-authentication-authorization-in-asp-net-core-explained\/"},"modified":"2026-05-10T14:21:24","modified_gmt":"2026-05-10T07:21:24","slug":"cookie-based-authentication-authorization-in-asp-net-core-explained","status":"publish","type":"post","link":"https:\/\/daiilynews.cu.ma\/?p=2819","title":{"rendered":"Cookie based authentication &#038; authorization in ASP.NET Core explained"},"content":{"rendered":"<p><br \/>\n<\/p>\n<p>Video &#8211; https:\/\/youtu.be\/GhZLi8pBJow?si=mnIVpCke9OJBMFoJ<\/p>\n<p>Services for Authentication and Authorization<\/p>\n<p>Authentication Service<\/p>\n<p>Maintains multiple authentication schemes<br \/>\nUses Cookie handler to Build ClaimsPrincipal from cookie, set up request redirection for login, logout, access denial<br \/>\nAdd cookie authentication service in DI container using the following<\/p>\n<p>\/\/ Add Cookie Authentication service<br \/>\nbuilder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)<br \/>\n    .AddCookie(options =><br \/>\n    {<br \/>\n        options.LoginPath = &#8220;\/Account\/Login&#8221;; \/\/ Specify the path to the login page<br \/>\n        options.AccessDeniedPath = &#8220;\/Account\/AccessDenied&#8221;; \/\/ Specify the path for access denied<br \/>\n        options.ExpireTimeSpan = TimeSpan.FromMinutes(60); \/\/ Set the cookie expiration time<br \/>\n        options.SlidingExpiration = true; \/\/ Enable sliding expiration<br \/>\n    });<\/p>\n<pre><code>Enter fullscreen mode\n\n\n\nExit fullscreen mode\n<\/code><\/pre>\n<p>AddAuthentication adds the authentication service to DI container. It also specifies the default authentication scheme (Cookies) for authentication.<br \/>\n  AddCookie provides a cookie authentication handler for the Cookies authentication scheme.<\/p>\n<p>Authorization Service<\/p>\n<p>Evaluates ClaimsPrincipal&#8217;s claims against authorization policies to determine if the request is authorized<br \/>\nAdd authorization service in DI container using the following<\/p>\n<p>builder.Services.AddAuthorization(options =><br \/>\n{<br \/>\n    \/\/ Define a rule named &#8220;AdminOnly&#8221;<br \/>\n    options.AddPolicy(&#8220;AdminOnly&#8221;, policy =><br \/>\n        policy.RequireRole(&#8220;Admin&#8221;)<br \/>\n              .RequireClaim(&#8220;EmployeeId&#8221;));<br \/>\n});<\/p>\n<pre><code>Enter fullscreen mode\n\n\n\nExit fullscreen mode\n<\/code><\/pre>\n<p>The above code adds a policy named AdminOnly along with default available authorization service policies<\/p>\n<p>A Request&#8217;s Journey for cookie-based Authentication and Authorization in dotnet<\/p>\n<p>Phase 1 &#8211; Authentication middleware (for Identification)<\/p>\n<p>Authentication middleware identifies the visitor by extracting the ClaimsPrincipal from cookie and attaches it to HttpContext<\/p>\n<p>Authenticaiton middleware is added to the request pipeline using the following<\/p>\n<p>app.UseAuthentication();<\/p>\n<pre><code>Enter fullscreen mode\n\n\n\nExit fullscreen mode\n<\/code><\/pre>\n<p>Steps<\/p>\n<p>Middleware asks the Authentication Service (configured via AddAuthentication) for a ClaimsPrincipal (user).<br \/>\nAuthentication Service calls the Cookie Handler. It decrypts the cookie (using Data Protection Provider) and creates a ClaimsPrincipal<br \/>\nThe created ClaimsPrincipal is attached to HttpContext.User. The request moves to the next middleware.<\/p>\n<p>Phase 2: Authorization middleware (for Permissions check)<\/p>\n<p>Authorization middleware evaluates the identified ClaimsPrincipal&#8217;s claims and redirects the request to login or denies the request if claims don&#8217;t meet the authorization requirements<br \/>\nAuthorization middleware is added to the request pipeline using the following<\/p>\n<p>app.UseAuthorization();<\/p>\n<pre><code>Enter fullscreen mode\n\n\n\nExit fullscreen mode\n<\/code><\/pre>\n<p>Steps<\/p>\n<p>Authorization middleware checks the endpoint for attributes like (Authorize) or a specific policy (e.g., (Authorize(Policy = &#8220;AdminOnly&#8221;))).<br \/>\nAuthorization middleware asks the Authorization Service (registered via AddAuthorization) to evaluate the ClaimsPrincipal&#8217;s claims against those rules.<br \/>\nBased on that evaluation, the system executes one of three paths:<\/p>\n<p>Path A: User is Not Logged In (Challenge the request)<\/p>\n<p>Condition: The authorization policy requires a user, but HttpContext.User is anonymous.<br \/>\nAction: The Authorization middleware triggers a Challenge by calling the ChallengeAsync method on the Authentication service.<br \/>\nExecution: Authentication service delegates the Challenge execution to Cookie Handler, which modifies HttpContext.Response for a 302 Redirect to LoginPath. The pipeline short-circuits.<\/p>\n<p>Path B: User has Wrong Permissions (Forbid the request)<\/p>\n<p>Condition: ClaimPrincipal is present, but the claims fail the requirements of authorization policies.<br \/>\nAction: The Authorization middleware triggers a Forbid by calling the ForbidAsync method on the Authentication service.<br \/>\nExecution: Authentication service delegates the Forbid execution to Cookie Handler, which modifies HttpContext.Response for a 302 Redirect to AccessDeniedPath. The pipeline short-circuits.<\/p>\n<p>Path C: Access Granted<\/p>\n<p>Condition: The user&#8217;s claims satisfy all requirements in the Authorization Service.<br \/>\nExecution: The middleware calls next(), allowing the request to reach next middleware (like controllers).<\/p>\n<p>Setting logged in user in the cookie<\/p>\n<p>The user will submit credentials in the login page<br \/>\n The user credentials will be verified from a database and ClaimsPrincipal will be created to represent the logged in user<br \/>\n HttpContext.SignInAsync uses Authentication service&#8217;s Cookie Handler to set the logged in user details (a ClaimsPrincipal) in the response cookie<\/p>\n<p>await HttpContext.SignInAsync(<br \/>\n    CookieAuthenticationDefaults.AuthenticationScheme,<br \/>\n    new ClaimsPrincipal(claimsIdentity),<br \/>\n    authProperties);<\/p>\n<pre><code>Enter fullscreen mode\n\n\n\nExit fullscreen mode\n<\/code><\/pre>\n<p>Signout logged in user<\/p>\n<p>await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);<\/p>\n<pre><code>Enter fullscreen mode\n\n\n\nExit fullscreen mode\n<\/code><\/pre>\n<p>HttpContext.SignOutAsync uses Authentication service&#8217;s Cookie Handler to expire the cookie that contains the logged in user details (a ClaimsPrincipal) and makes the HttpContext.User as anonymous<\/p>\n<p>Access the ClaimsPrincipal (logged in user)<\/p>\n<p>After the authentication middleware derives a valid ClaimsPrincipal from the cookie, it sets the user details (ClaimsPrincipal) in the HttpContext.User object<br \/>\n  Hence<\/p>\n<p>HttpContext.User?.Identity?.IsAuthenticated can be used to determine if a request is authenticated<br \/>\n  HttpContext.User.Identity.Name can be used to determine the logged in user name<\/p>\n<p><br \/>\n<br \/><a href=\"https:\/\/dev.to\/nagasudhirpulla\/cookie-based-authentication-authorization-in-aspnet-core-explained-1k8l\">Source link <\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Video &#8211; 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 = &#8220;\/Account\/Login&#8221;; \/\/ Specify [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":2820,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[676],"tags":[761,765,1144,762,1145,763,764,1086,760,795],"class_list":["post-2819","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tech-ai","tag-coding","tag-community","tag-csharp","tag-development","tag-dotnet","tag-engineering","tag-inclusive","tag-security","tag-software","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/daiilynews.cu.ma\/index.php?rest_route=\/wp\/v2\/posts\/2819","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/daiilynews.cu.ma\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/daiilynews.cu.ma\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/daiilynews.cu.ma\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/daiilynews.cu.ma\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2819"}],"version-history":[{"count":0,"href":"https:\/\/daiilynews.cu.ma\/index.php?rest_route=\/wp\/v2\/posts\/2819\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/daiilynews.cu.ma\/index.php?rest_route=\/wp\/v2\/media\/2820"}],"wp:attachment":[{"href":"https:\/\/daiilynews.cu.ma\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2819"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/daiilynews.cu.ma\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2819"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/daiilynews.cu.ma\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2819"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}