ASP.NET Core Identity+JWT Token API授权失效问题求助
ASP.NET Core 8.0 API授权失效,调用接口返回404/302的问题排查与解决
问题根源分析
- 302重定向问题:ASP.NET Identity默认启用Cookie认证,未授权请求会被重定向到登录页面,这不符合API场景的预期(应返回401 Unauthorized)。
- JWT验证参数不完整:
TokenValidationParameters默认开启ValidateIssuer和ValidateAudience,但你的JWT生成与验证配置均未指定Issuer、Audience,导致验证失败。 - 默认认证Scheme冲突:
AddIdentity会将Cookie认证注册为默认Scheme,而你配置的JWT Bearer未设为默认,导致[Authorize]特性优先使用Cookie认证,触发重定向。 - 路由匹配问题(404):请求地址或方法不符合接口路由规则,比如未使用POST方法、路径拼写错误。
修复步骤
1. 修正JWT认证配置,设置默认Scheme并完善验证逻辑
修改Program.cs中的认证配置,指定JWT为默认Scheme,并处理认证失败的响应:
builder.Services.AddAuthentication(options => { // 设置JWT为默认认证Scheme options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(option => { option.SaveToken = true; option.TokenValidationParameters = new TokenValidationParameters { RequireExpirationTime = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:IssuerSigningKey"])), // 若不需要验证Issuer和Audience,设置为false;若需要则配置ValidIssuer和ValidAudience ValidateIssuer = false, ValidateAudience = false }; // 强制认证失败时返回401而非302 option.Events = new JwtBearerEvents { OnChallenge = context => { context.HandleResponse(); context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.ContentType = "application/json"; return context.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(new { message = "未授权访问" })); } }; });
2. 禁用Identity默认Cookie重定向
在AddIdentity配置后添加以下代码,关闭Cookie认证的重定向行为:
builder.Services.ConfigureApplicationCookie(options => { options.Events.OnRedirectToLogin = context => { context.Response.StatusCode = StatusCodes.Status401Unauthorized; return Task.CompletedTask; }; });
3. 完善JWT Token生成逻辑
补充标准声明,同时使用UTC时间避免时区问题:
public async Task<IActionResult> Login([FromBody] UsersLoginModel model) { if (ModelState.IsValid) { // 替换为实际的UserManager验证逻辑 var user = await _userManager.FindByNameAsync(model.Username); var resultIdentity = await _userManager.CheckPasswordAsync(user, model.Password); if (resultIdentity) { var key = _config["JWT:IssuerSigningKey"]; var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)); // 添加标准用户标识声明 var claims = new List<Claim> { new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim("id", model.Username) }; var tokenObject = new JwtSecurityToken( claims: claims, expires: DateTime.UtcNow.AddMinutes(10), // 使用UtcNow避免时区导致的过期错误 signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)); var resultJwt = new JwtSecurityTokenHandler().WriteToken(tokenObject); return Ok(resultJwt); } } return Unauthorized(); }
4. 确认请求规则
确保请求满足以下要求:
- 请求方法:POST
- 请求地址:
https://你的域名/Upload/Uploadtest - 请求头包含:
Authorization: Bearer {你的JWT Token}
内容的提问来源于stack exchange,提问作者YaSecu
相关产品推荐
相关产品推荐

