我正在尝试在.NET Core 3 Preview 5 Web API项目中从Swashbuckle的4.0.1版本迁移到5.0.0-rc2。
我已经完成了项目的编译,并且Swagger UI正常运行,但是我无法使Bearer身份验证正常工作,这是由于我没有正确设置新格式的安全性。
这是我在版本4中使用的旧代码:
c.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
var security = new Dictionary<string, IEnumerable<string>>
{
{"Bearer", new string[] { }},
};
c.AddSecurityRequirement(security);
Run Code Online (Sandbox Code Playgroud)
这就是我将其更改为v5的内容:
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] …Run Code Online (Sandbox Code Playgroud) 我搜索了添加请求标头参数的可能方法,该参数将自动添加到我的每个方法中,web-api但我找不到清楚的方法.
在搜索时我发现该方法OperationFilter()必须对此做些什么.
我使用由我的应用程序的身份验证服务生成的令牌.没有问题.现在我已经介绍了Swashbuckle以记录我的API,我可以通过使用此代码向JWT发送每个请求来进行身份验证.
services.AddSwaggerGen(c =>
{
var a = new ApiKeyScheme();
//c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
//{ In = "header", Description = "Please insert JWT with Bearer into field", Name = "Authorization", Type = "apiKey" });
c.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
c.SwaggerDoc("v2", new Info
{
Version = "v2",
Title = "MyTitle",
Description = "An interface for ...",
TermsOfService = "None",
Contact = new Contact() { Name = "MyApp", Email = "a@example.com", Url = "www.example.com" }
});
// Set the comments path for the Swagger JSON and UI.
var …Run Code Online (Sandbox Code Playgroud)