惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
博客园 - 司徒正美
博客园 - 【当耐特】
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
IT之家
IT之家
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
酷 壳 – CoolShell
酷 壳 – CoolShell
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
大猫的无限游戏
大猫的无限游戏
月光博客
月光博客
宝玉的分享
宝玉的分享
V
V2EX
S
SegmentFault 最新的问题
V
Visual Studio Blog
阮一峰的网络日志
阮一峰的网络日志
Martin Fowler
Martin Fowler
Jina AI
Jina AI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园_首页
L
LangChain Blog
D
Docker
腾讯CDC

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Cookie based authentication & authorization in ASP.NET Co...
Nagasudhir P · 2026-05-10 · via DEV Community

Nagasudhir Pulla

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