将我的网站从.NET Core 2.2迁移到3.1.1之后,我的api端点突然开始尝试将api请求重定向到默认登录页面(/Account/Login?ReturnUrl = ,我什至没有任何路线.
After migrating my website from .NET Core 2.2 to 3.1.1, my api endpoints suddenly started trying to redirect my api request to a default login page (/Account/Login?ReturnUrl=, which I don't even have in any of my routes).
我的api使用的是JWT承载身份验证方案和JWT挑战方案,但是仍然发生了重定向.
My api is using a JWT bearer authentication scheme, with JWT Challenge Scheme, but still the redirect happened.
services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; })我终于找到了解决这个问题的方法,但是我不知道为什么它真的有帮助.
I finally found a solution to the problem, but I have no idea why it actually helped.
最初,我将服务设置为:
Initially I had my services set as:
services .AddIdentity<IdentityUser, IdentityRole>() .AddSignInManager() .AddEntityFrameworkStores<CleWebToolsIdentityDbContext>();但这确实进行了重定向.
But that did the redirect.
最终解决我问题的方法是将它们设置为:
What finally solved my problem was setting them to:
services .AddIdentityCore<IdentityUser>() .AddRoles<IdentityRole>() .AddSignInManager() .AddEntityFrameworkStores<CleWebToolsIdentityDbContext>();有人可以告诉我这是怎么回事吗?
Can somebody tell me what is going on here?
即使质询方案应为JWT,AddIdentity方法如何导致重定向?
How does the AddIdentity-method cause the redirect, even though the challenge scheme should be JWT?
推荐答案这是因为 AddIdentity 为应用程序本身,外部登录(例如Facebook和Google)注册了默认的基于Cookie的身份验证方案)和2FA.如果将 services.AddIdentity< IdentityUser,IdentityRole>()放在 AddJwtBearer 配置下面,它将重置默认架构,要避免这种情况,可以将Identity配置放在jwt承载配置:
That is because AddIdentity registers the default Cookie-based authentication schemes for the application itself, external sign-in (e.g. Facebook and Google), and 2FA . It will reset the default schema if you put services.AddIdentity<IdentityUser, IdentityRole>() below the AddJwtBearer config , to avoid this , you can put the identity config above the jwt bearer config :
services .AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders().AddDefaultUI(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { .... });使用 AddIdentityCore 之所以有效,是因为它不会注册默认的基于Cookie的身份验证方案,请参见 AddIdentity与AddIdentityCore 了解更多详细信息.
Use AddIdentityCore works because it won't registers the default Cookie-based authentication schemes , see AddIdentity vs AddIdentityCore for more details.
更多推荐
从ASP.NET Core 2.2迁移后,ASP.NET Core 3.1.1 Jwt重定向而不是返回HTTP状态401
发布评论