ASP.NET Core Web API使用JWT实现Token认证时授权请求返回401
我正在为我的Web API配置基于Token的身份验证。目前我可以正常生成Token,但在使用Token进行授权时遇到问题:通过Postman测试时,所有受保护的POST请求都返回401 Unauthorized。
我在Token相关开发上经验较少,已经尝试调整过中间件管线顺序但问题仍未解决,不清楚该如何排查,以下是我当前的配置代码:
Startup.cs 配置
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } private IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; }); services.AddMvc(); services.AddControllers(); services.AddSingleton<ITitleDataService, TitleDataService>(); services.AddSingleton<IPersonDataService, PersonDataService>(); services.AddSingleton<IUserDataService, UserDataService>(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddControllersWithViews() .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); services.AddMvc().AddControllersAsServices(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRequestLogging(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseFileServer(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }
控制器代码
// LOGIN接口 [HttpPost("user/login/")] public IActionResult Login(UserDto userDto) { var user = _dataService.Login(userDto.Username, userDto.Password); IActionResult response = Unauthorized(); if (user) { var tokenStr = GenerateJSONWebToken(userDto); response = Ok(new {tokenStr}); } else { return BadRequest("User not authorized"); } return response; } [Authorize] [HttpPost("post")] public string Post() { var identity = HttpContext.User.Identity as ClaimsIdentity; IList<Claim> claim = identity.Claims.ToList(); Console.WriteLine(claim.Count); var username = claim[0].Value; Console.WriteLine(username); return "Welcome to " + username; } [Authorize] [HttpGet("GetValue")] public ActionResult<IEnumerable<string>> Get() { return new string[] {"Value1", "Value2", "Value3"}; } private string GenerateJSONWebToken(UserDto userDto) { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userDto.Username), new Claim(JwtRegisteredClaimNames.Email, userDto.Password), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; var token = new JwtSecurityToken( issuer: "Issuer", audience: "Issuer", claims, expires: DateTime.Now.AddMinutes(120), signingCredentials: credentials); var encodetoken = new JwtSecurityTokenHandler().WriteToken(token); return encodetoken; }
问题排查与解决方案
直接对照你的代码按优先级处理以下问题:
1. 补充Token验证参数缺失的Issuer、Audience配置
你开启了ValidateIssuer和ValidateAudience校验,但没有在验证参数里指定合法的Issuer、Audience值。你生成Token时指定的issuer和audience都是字符串"Issuer",但中间件默认会校验空值,直接导致Token校验不通过。
修改AddJwtBearer里的配置:
options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = "Issuer", // 和生成Token的issuer完全对应 ValidateAudience = true, ValidAudience = "Issuer", // 和生成Token的audience完全对应 ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) };
2. 清理重复的MVC服务注册
你在ConfigureServices里重复调用了AddMvc、AddControllers、AddControllersWithViews三套注册逻辑,会导致配置冲突。尤其是AddControllersWithViews会默认启用 antiforgery 防伪令牌验证,所有非GET请求都会被校验是否附带有效的防伪头,否则直接返回401/400,刚好匹配你只有POST请求失败的现象。
如果是纯Web API项目,直接删掉多余的注册,只保留一套配置:
// 纯Web API不需要AddControllersWithViews,删掉所有多余的AddMvc、AddControllersWithViews调用 services.AddControllers() .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore );
如果确实需要兼容MVC视图,就在需要跳过防伪校验的POST方法上加[IgnoreAntiforgeryToken]特性。
3. 检查Postman请求的Authorization头配置
确认请求的鉴权头格式完全正确:
- 选择Postman的
Authorization标签,类型选Bearer Token,直接把生成的Token粘贴到输入框,不要手动拼Header - 如果手动拼Header,必须是
Authorization: Bearer 你的Token字符串,注意Bearer后面有一个空格,不要漏加或者多打字符
4. 检查JWT密钥长度
SymmetricSecurityKey要求密钥长度至少为128位(也就是16字节的ASCII字符串),如果你在appsettings.json里配置的Jwt:Key长度少于16个字符,会直接导致签名校验失败。
修改appsettings.json的Jwt配置,把密钥改成长度至少16位的随机字符串:
"Jwt": { "Key": "至少16位的随机密钥,比如你自己生成的长字符串" }
5. 开启错误日志定位具体校验问题
如果改完上面的问题还是没解决,直接加JWT校验失败的日志输出,就能看到具体是哪一步校验不通过:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { // 你原来的TokenValidationParameters配置 options.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { // 把错误打印到控制台,直接看失败原因 Console.WriteLine($"Token校验失败:{context.Exception.Message}"); return Task.CompletedTask; } }; });
跑程序发请求后看控制台输出,就能直接定位是issuer不匹配、audience不匹配、签名错误还是Token过期。
内容的提问来源于stack exchange,提问作者JesperEriksen

