我在获取输入到swagger UI中以附加到发送的请求的承载授权标头时遇到麻烦。我在用户界面上有authorize选项,但它实际上什么也没做
我已经看过一堆教程,但是似乎大张旗鼓可能改变了它们附加标题的方式,所以我很挣扎。我非常有信心,我需要使用'AddSecurityRequirement()'函数,但是我知道如何创建正确的对象以传递给它。
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Message Service", Version = "v1" });
var security = new Dictionary<string, IEnumerable<string>>
{
{ "Bearer", new string[] { } },
};
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
// Im not sure how to get the token to apply to the header being called. It will get the token, but it doesnt apply it to the request
c.AddSecurityRequirement(/*What goes here???? I tried passing security object above but no dice.*/);
var xmlDocFile = Path.Combine(AppContext.BaseDirectory, "MessageService.xml");
if (File.Exists(xmlDocFile))
{
var comments = new XPathDocument(xmlDocFile);
c.OperationFilter<XmlCommentsOperationFilter>(comments);
c.SchemaFilter<XmlCommentsSchemaFilter>(comments);
}
});
我希望标头可以附加到请求中,但是没有附加,所以我从api中获得了401。
答案 0 :(得分:5)
要增加安全性要求,通常需要传递一个新的OpenApiSecurityRequirement
实例。根据您当前的设置,以下内容可能会满足您的要求。
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});