You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 13:57:18