【发布时间】:2020-01-19 09:41:18
【问题描述】:
我在 dotnet core 3.1 web api 项目中使用 Swagger Swashbuckle,无法向请求调用发送不记名授权。
我在 ConfigureServices 方法中定义了这个:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo() { Title = "MyApi", Version = "v1" });
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows()
{
Password = new OpenApiOAuthFlow()
{
TokenUrl = new Uri("/api/Account/Login", UriKind.Relative),
}
},
In = ParameterLocation.Header,
Name = "Authorization",
Scheme = "Bearer",
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme()
{
Reference = new OpenApiReference()
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "Bearer",
Type = SecuritySchemeType.Http,
Name = "Bearer",
In = ParameterLocation.Header
}, new List<string>()
}
});
});
登录后,API 路由显示锁定的挂锁,但当我尝试使用它们时,我看到调用完成时没有返回的承载:
curl -X GET "http://localhost:5000/api/Account" -H "accept: */*" -H "Authorization: Bearer undefined"
我的定义有什么问题?
【问题讨论】:
-
所以当您调用您的服务时,您的不记名令牌没有从标头中的客户端发送?这不是您的服务的问题,而是您的客户的问题。
-
@tomredfern 是的,客户很招摇。
-
Swashbuckle 不支持您尝试执行的操作。改用邮递员之类的东西。
-
很可能,
AddSecurityRequirement被调用时使用了错误的参数。您可以从生成的 OpenAPI JSON/YAML 文件中发布securitySchemes和security部分吗?
标签: .net-core authorization swagger asp.net-core-webapi bearer-token