c# - 如何将不记名授权标头附加到招摇请求。Swashbuckle v 5.0.0-rc2
问题描述
我无法获取输入到 swagger UI 以附加到发送的请求的不记名授权标头。我在 UI 上有授权选项,但它基本上什么都不做
我已经浏览并查看了一堆教程,但似乎大摇大摆可能已经改变了他们附加标题的方式,所以我很挣扎。我相当有信心我需要使用“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。
解决方案
要添加安全要求,您通常需要传入一个新OpenApiSecurityRequirement
实例。鉴于您当前的设置,以下可能满足您的要求。
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
推荐阅读
- kotlin - 将 Jetbrains 暴露的库与 Ktor 一起使用并在协程内执行数据库事务是否安全?
- javascript - 表单验证 - 电子邮件、姓名和签名
- azure-language-understanding - 处理列表实体上的拼写错误
- python - 从子进程调用时无法将参数传递给python脚本
- php - 如何使用带有访问令牌的 php 将文件上传到谷歌驱动器
- html - 当我为移动设备调整页脚大小时,页脚和页面底部之间有一个空白区域
- database - 我的信息没有发送到我的数据库
- html - Safari 中的三角形按钮颜色问题(纯 CSS)
- javascript - 在类组件中使用 React 钩子
- ruby-on-rails - 由 config.action_cable.url 定义的 URL 在被 Vue 前端使用时生成 404