ASP.NET 6 API身份验证:Cookie未存储Claims问题求助
ASP.NET 6 API身份验证:登录后Claims为空的解决方法
你的代码问题出在没有将身份验证中间件加入请求管道,导致请求到达/username端点时,ASP.NET不会自动解析Cookie并填充ctx.User的Claims。
解决步骤:
在var app = builder.Build();之后、注册端点之前,添加以下两行中间件:
app.UseAuthentication(); app.UseAuthorization();
修改后的完整代码:
using System.Security.Claims; using Microsoft.AspNetCore.Authentication; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthentication("cookie") .AddCookie("cookie"); var app = builder.Build(); // 添加身份验证和授权中间件,必须在端点注册之前 app.UseAuthentication(); app.UseAuthorization(); app.MapGet("/username", (HttpContext ctx) => { var allClaims = ctx.User.Claims.ToList(); var userName = ctx.User.FindFirst("usr"); return userName?.Value ?? "usr not found in claims"; }); app.MapGet("/login", async (HttpContext ctx) => { var claims = new List<Claim> { new Claim("usr", "mariano") }; var identity = new ClaimsIdentity(claims, "cookie"); var user = new ClaimsPrincipal(identity); var authProperties = new AuthenticationProperties { AllowRefresh = true, ExpiresUtc = DateTimeOffset.Now.AddDays(1), IsPersistent = true }; await ctx.SignInAsync("cookie", user, authProperties); return "ok"; }); app.Run();
关键说明:
AddAuthentication仅在DI容器中配置身份验证服务,而UseAuthentication才会将身份验证逻辑注入请求管道,负责读取Cookie中的身份信息并填充ctx.User。- 中间件顺序很重要:
UseAuthentication必须在UseAuthorization和端点注册之前调用,确保请求先经过身份验证流程。
内容的提问来源于stack exchange,提问作者Mariano Gomez Bidondo
相关产品推荐
相关产品推荐

