当我通过swagger将令牌发送到api时,我仍然得到401未经授权
Content-Length:0 Date:Sat,2020年6月6日12:51:50 GMT服务器:Microsoft-IIS/8.5 Strict-Transport-Security:max-age=2592000
www-Authenticate:Bearer Error=“Invalid_Token”,Error_Description=“The signature is Invalid”X-powered-by:ASP.NET
这是我的ConfigureReservices配置
services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "App Manager - Running Buddies", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme {
Description = "JWT Authorization header using the Bearer scheme.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement{
{
new OpenApiSecurityScheme{
Reference = new OpenApiReference{
Id = "Bearer", //The name of the previously defined security scheme.
Type = ReferenceType.SecurityScheme
}
},new List<string>() }
});
});
services.AddTokenAuthentication(Configuration);
我的AddTokenAuthentication调用,它是配置认证JWT承载的扩展,当它是barrer令牌时,它可以不允许测试
public static class AddTokenAuthentications {
public static IServiceCollection AddTokenAuthentication(this IServiceCollection services, IConfiguration config) {
var secret = config.GetSection("JwtToken").GetSection("SecretKey").Value;
var keySecret = Base64UrlEncoder.DecodeBytes(secret);
var key = Encoding.ASCII.GetBytes(keySecret.ToString());
services.AddAuthentication(x => {
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x => {
{
// x.Audience = config.GetSection("JwtToken").GetSection("Audience").Value;
// x.Authority = config.GetSection("JwtToken").GetSection("Authority").Value;
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
}
});
return services;
}
如果我的理解是正确的,我猜你没有添加API键或实现操作过滤器。 因此,您想要测试需要使用swagger进行身份验证的API,您必须在swagger配置中添加API密钥或实现IOOperationFilter,它允许您在swagger上输入JWT令牌。 完成此操作后,您可以测试您的API。
这些文章供大家参考: