我正在将 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 令牌验证的中间件已经到位。有什么建议么?谢谢!