ASP.NET Core 2.0授权失败:用户为null的问题排查求助
问题排查与解决方案
我仔细看了你的代码和问题描述,核心问题出在认证Scheme的冲突上——你的项目同时启用了ASP.NET Identity(Cookie认证)和IdentityServer的JWT认证,但默认的认证Scheme是Cookie,而你的Aurelia客户端发送的是JWT Bearer令牌,导致API的认证中间件无法正确识别并验证令牌,最终User为null。
下面是具体的修复步骤:
1. 修正认证Scheme配置
在Startup.ConfigureServices中,明确将IdentityServer的JWT认证设置为默认的认证Scheme,这样API端点会优先使用JWT验证:
services.AddAuthentication(options => { // 设置默认的认证和挑战Scheme为IdentityServer的JWT认证 options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; }) .AddIdentityServerAuthentication(options => { options.Authority = Config.HOST_URL + "/"; options.RequireHttpsMetadata = false; options.ApiName = "api1"; });
2. 调整中间件顺序(移除重复的认证中间件)
app.UseIdentityServer()已经包含了认证中间件的逻辑,重复调用app.UseAuthentication()会导致冲突,所以需要从Configure方法中移除这一行,同时确保中间件顺序正确:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); // IdentityServer必须在CORS和Mvc之前 app.UseIdentityServer(); // CORS中间件要放在Mvc之前,确保跨域请求被正确处理 app.UseCors("default"); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
3. 可选:为单个API控制器指定认证Scheme
如果你不想修改全局默认Scheme,也可以在需要授权的API控制器上显式指定认证Scheme:
using Microsoft.AspNetCore.Authentication; using IdentityServer4.AccessTokenValidation; [Authorize(AuthenticationSchemes = IdentityServerAuthenticationDefaults.AuthenticationScheme)] public class YourApiController : ControllerBase { // ...你的API方法 }
额外验证点
- 确认客户端发送请求时,Authorization头的格式是
Bearer <你的token>,你的token内容看起来是正确的(包含aud: ["api1"],和options.ApiName匹配)。 - 确保你的API控制器上添加了
[Authorize]属性(你提到进行用户授权,应该已经加了,但还是确认一下)。
按照上面的步骤修改后,API应该能正确验证JWT令牌,并获取到用户信息了。
内容的提问来源于stack exchange,提问作者graycrow
相关产品推荐
相关产品推荐

