And*_*ton 5 c# swagger swagger-ui .net-core
我无法获取我输入到 swagger UI 以附加到发送的请求的承载授权标头。我在用户界面上有授权选项,但它基本上什么都不做
我已经浏览并查看了一堆教程,但似乎 swagger 可能改变了他们附加标题的方式,所以我很挣扎。我相当有信心我需要使用 '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);
}
});
Run Code Online (Sandbox Code Playgroud)
我希望标头附加到请求,但它没有附加,所以我从我的 api 中得到了 401。
要添加安全要求,您通常需要传入一个新OpenApiSecurityRequirement
实例。鉴于您当前的设置,以下可能满足您的要求。
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1784 次 |
最近记录: |