我在asp.net核心应用程序中实现了Jwt的授权,但是我用[Authorize(AuthenticationSchemes = "AccessKey")]
装饰的所有端点都收到401错误,即使我在请求标头中传递了正确的访问密钥也是如此。>
这是我的Jwt实现
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateActor = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = appSettings.SecurityConfiguration.TokenIssuer,
ValidAudience = appSettings.SecurityConfiguration.AppName,
IssuerSigningKey =
new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(appSettings.SecurityConfiguration.IssuerSigningKey))
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
if (context.Request.Path.Value.Contains("/hubs/notification") &&
context.Request.Query.TryGetValue("access_token", out StringValues token)
)
{
context.Token = token;
}
return Task.CompletedTask;
},
OnAuthenticationFailed = context =>
{
return Task.CompletedTask;
}
};
options.ForwardDefaultSelector = ctx =>
ctx.Request.IsAccessKeyRequest(appSettings) ? AccessKeyAuthOptions.DefaultScheme : null;
}).AddAccessKeyAuthentication(options =>
{
});
AddAccessKeyAuthentication
扩展方法在下面实现
public static void AddAccessKeyAuthentication(this AuthenticationBuilder builder, Action<AccessKeyAuthOptions> configureOptions)
{
builder.AddScheme<AccessKeyAuthOptions, AccessKeyAuthenticationHandler>(AccessKeyAuthOptions.DefaultScheme, configureOptions);
}
我通读了一些过去解决的问题,大多数建议在Startup类的configure方法中添加app.UseAuthorization()
,但遇到IApplicationBuilder doesn't contain definition for UseAuthorization and no extension method..
错误,我使用的是.net core 2.2,我可以在这里找不到它。升级到3.x对我来说不是一个选择,因为我有很多事情取决于2.2。请有人帮助找出问题所在