将 API 迁移到 .net Core 3 时出现 JWT 401 未经授权的错误
Posted
技术标签:
【中文标题】将 API 迁移到 .net Core 3 时出现 JWT 401 未经授权的错误【英文标题】:JWT 401 unauthorized error on migrating API to .net Core 3 【发布时间】:2019-12-25 16:18:44 【问题描述】:我正在将 Web API 从 .net core 2 迁移到 3.1,并且遇到了 [Authorize] 所需端点的问题。即使我正在发送授权持有者令牌,我也会获得 401 未授权。 我想我需要在启动类上配置服务的方式进行一些更改,但无法弄清楚。
这是我的 Startup.cs 文件:
public class Startup
public Startup(IWebHostEnvironment env)
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
public IConfiguration Configuration get;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
options.TokenValidationParameters = new TokenValidationParameters
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "OhmioWEBApi",
ValidAudience = "OhmioWEBClient",
IssuerSigningKey = JwtSecurityKey.Create("Secret_key")
;
options.Events = new JwtBearerEvents
OnAuthenticationFailed = context =>
Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
return Task.CompletedTask;
,
OnTokenValidated = context =>
Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
return Task.CompletedTask;
;
);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IConfiguration>(Configuration);
services.AddAutoMapper(typeof(MapsProfile));
EntityFrameworkConfiguration.ConfigureService(services, Configuration);
IocContainerConfiguration.ConfigureService(services);
services.AddControllers();
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
endpoints.MapControllers();
);
正如您所见,用于 JWT 令牌验证的中间件已经到位。 有什么建议? 谢谢!
【问题讨论】:
在您的配置方法中添加app.UseAuthentication();
。请参阅此文档以迁移到 .NET CORE 3.0:docs.microsoft.com/en-us/aspnet/core/migration/…
【参考方案1】:
尝试添加以下代码sn-p:
services.AddAuthentication(x =>
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
)
.AddJwtBearer(x =>
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
;
);
【讨论】:
谢谢,结果还是一样:401未授权 您的代码中缺少的另一件事是:app.UseAuthentication(); 是的!这样做。我需要同时添加 app.UseAuthentication();和 app.UseAuthorization(); (按特定顺序)在 StartUp 上进行配置并开始工作!谢谢 app.UseAuthentication()的诡计;和 app.UseAuthorization();按这个顺序确实救了我的命!以上是关于将 API 迁移到 .net Core 3 时出现 JWT 401 未经授权的错误的主要内容,如果未能解决你的问题,请参考以下文章
将 asp.net core web api 部署到 IIS 7.5 时出现 500 错误
将 asp.net core web api 部署到 aws elastic beanstalk 时出现错误 404
如何将 .NET Core 2.2 Web API 迁移到 .NET Core 3.0?
Angular 8 使用 ASP NET Core 3.1 Web Api 时出现 CORS 策略问题
如何将 .net core Web API 项目添加到现有的 .NET core (3.1) Web Application 项目中?