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

ASP.NET Core 5.0 JWT认证访问[Authorize]接口返回401及CORS异常求助

问题原因汇总

  • CORS配置冲突且位置错误:ConfigureServices中同时配置了AllowAnyOrigin和AllowCredentials,二者属于CORS协议互斥规则;同时Configure中UseCors放在了认证授权中间件之后,配置不生效。
  • JWT认证默认读取规则不匹配:JWTBearer中间件默认从Authorization请求头读取Bearer格式的Token,你的Token存在Cookie中,跳转请求不会自动把Cookie值塞到请求头里,导致中间件拿不到Token返回401。
  • JWT密钥长度不足:SymmetricSecurityKey要求密钥至少为16位字符,你当前配置的TestProdigy长度不满足要求,签名校验直接失败。
  • 登录接口请求方式不匹配:Login接口标记了[HttpPost],但页面上的TestLogin跳转是GET请求,根本无法触发登录逻辑生成Token。
  • 终端pty报错属于Visual Studio/VS Code的终端进程异常,和业务代码无关。

可行解决方案

1. 修复CORS配置

如果是同域项目可以直接删除所有CORS相关代码,不需要跨域配置;如果确实需要跨域,按以下方式修改:

修改ConfigureServices中的CORS定义

services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", builder => 
        builder.WithOrigins("https://localhost:4200") // 替换为实际需要允许的跨域源
               .AllowAnyMethod()
               .AllowAnyHeader()
               .AllowCredentials());
});

调整Configure中的中间件顺序

UseCors必须放在UseRouting之后、认证授权中间件之前:

app.UseRouting();
app.UseCors("CorsPolicy"); // 直接引用已定义的策略名
app.UseAuthentication();
app.UseAuthorization();
// 删除原来放在这里的UseCors代码

2. 配置JWT从Cookie读取Token

修改AddJwtBearer配置,添加事件读取Cookie中的JWT值:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.IncludeErrorDetails = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType ="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
        RoleClaimType ="http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = Configuration["Jwt:Issuer"],
        ValidAudience = Configuration["Jwt:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
    };
    // 新增事件逻辑,从Cookie获取Token
    options.Events = new JwtBearerEvents
    {
        OnMessageReceived = context =>
        {
            context.Token = context.Request.Cookies["jwt"];
            return Task.CompletedTask;
        }
    };
});

3. 调整JWT密钥长度

修改appsettings.json中的Jwt:Key,替换为至少16位的字符串,例如:

"Jwt": {
  "Key": "TestProdigy12345678",
  "Issuer": "Test.mail.com"
}

4. 修复登录请求逻辑

两种方案二选一:

  1. 去掉Login方法的[HttpPost]特性,支持GET请求触发登录
  2. 把页面的TestLogin按钮改成表单提交按钮,触发POST请求:
<button type="submit" asp-action="Login" class="btn btn-light">TestLogin</button>

5. 可选优化

  • 统一Cookie过期时间和JWT过期时间,避免Cookie过期但Token未过期的问题
  • 删除Oper方法上的[HttpGet("Home/Oper")]特性,避免和默认路由冲突

内容的提问来源于stack exchange,提问作者Paul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 02:15:05