我正在使用 swagger 开发最小的 API,并且无需任何身份验证即可正常工作。但是当我添加身份验证时,它会显示错误。
这是我使用的代码。
应用设置.json
{
"AppSettings": {
"Token": "12345678912345678"
}
程序.cs
builder.Services.AddSwaggerGen(x =>
{
x.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "some description of the authorization mechanism",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
x.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
},new List<string>()
}
});
x.OperationFilter<SecurityRequirementsOperationFilter>();
});
和
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(x =>
{
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
当我运行项目时,它向我显示以下错误
注释掉 operationfilter 方法后,错误消失但授权仍然不起作用。