我在API中有一些端点 - /user/login
,/products
。
在Swagger UI中,我将email
和password
发布到/user/login
,作为回复,我收到了token
字符串。
然后,我可以从响应中复制令牌,并希望将其作为Authorization
标头值用于所有网址的请求(如果存在),并以/products
为例。
我应该在Swagger UI页面的某处手动创建文本输入,然后将令牌放在那里并以某种方式注入请求或是否有工具以更好的方式管理它?
答案 0 :(得分:41)
在ASP.net WebApi上,在Swagger UI上传入标头的最简单方法是在 IOperationFilter 界面上实现 Apply(...)方法。
将此添加到您的项目中:
public class AddRequiredHeaderParameter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
operation.parameters.Add(new Parameter
{
name = "MyHeaderField",
@in = "header",
type = "string",
description = "My header field",
required = true
});
}
}
在 SwaggerConfig.cs 上,使用 c.OperationFilter&lt; T&gt;()注册上面的过滤器:
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "YourProjectName");
c.IgnoreObsoleteActions();
c.UseFullTypeNameInSchemaIds();
c.DescribeAllEnumsAsStrings();
c.IncludeXmlComments(GetXmlCommentsPath());
c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
c.OperationFilter<AddRequiredHeaderParameter>(); // Add this here
})
.EnableSwaggerUi(c =>
{
c.DocExpansion(DocExpansion.List);
});
}
答案 1 :(得分:31)
您可以在请求中添加标头参数,Swagger-UI会将其显示为可编辑的文本框:
swagger: "2.0"
info:
version: 1.0.0
title: TaxBlaster
host: taxblaster.com
basePath: /api
schemes:
- http
paths:
/taxFilings/{id}:
get:
parameters:
- name: id
in: path
description: ID of the requested TaxFiling
required: true
type: string
- name: auth
in: header
description: an authorization header
required: true
type: string
responses:
200:
description: Successful response, with a representation of the Tax Filing.
schema:
$ref: "#/definitions/TaxFilingObject"
404:
description: The requested tax filing was not found.
definitions:
TaxFilingObject:
type: object
description: An individual Tax Filing record.
properties:
filingID:
type: string
year:
type: string
period:
type: integer
currency:
type: string
taxpayer:
type: object
您还可以添加类型为apiKey
的安全性定义:
swagger: "2.0"
info:
version: 1.0.0
title: TaxBlaster
host: taxblaster.com
basePath: /api
schemes:
- http
securityDefinitions:
api_key:
type: apiKey
name: api_key
in: header
description: Requests should pass an api_key header.
security:
- api_key: []
paths:
/taxFilings/{id}:
get:
parameters:
- name: id
in: path
description: ID of the requested TaxFiling
required: true
type: string
responses:
200:
description: Successful response, with a representation of the Tax Filing.
schema:
$ref: "#/definitions/TaxFilingObject"
404:
description: The requested tax filing was not found.
definitions:
TaxFilingObject:
type: object
description: An individual Tax Filing record.
properties:
filingID:
type: string
year:
type: string
period:
type: integer
currency:
type: string
taxpayer:
type: object
securityDefinitions
对象定义了安全方案。
security
对象(称为&#34;安全要求&#34;在Swagger-OpenAPI中),将安全方案应用于给定的上下文。在我们的案例中,我们通过将安全要求声明为顶级来将其应用于整个API。我们可以选择在单个路径项和/或方法中覆盖它。
这是指定安全方案的首选方式;它取代了第一个例子中的header参数。不幸的是,Swagger-UI并没有提供一个文本框来控制这个参数,至少在我目前的测试中是这样。
答案 2 :(得分:16)
在ASP.NET Core 2 Web API
中,使用Swashbuckle.AspNetCore包2.1.0,实现IDocumentFilter:
SwaggerSecurityRequirementsDocumentFilter.cs
using System.Collections.Generic;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace api.infrastructure.filters
{
public class SwaggerSecurityRequirementsDocumentFilter : IDocumentFilter
{
public void Apply(SwaggerDocument document, DocumentFilterContext context)
{
document.Security = new List<IDictionary<string, IEnumerable<string>>>()
{
new Dictionary<string, IEnumerable<string>>()
{
{ "Bearer", new string[]{ } },
{ "Basic", new string[]{ } },
}
};
}
}
}
在Startup.cs中,配置安全性定义并注册自定义过滤器:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
// c.SwaggerDoc(.....
c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
{
Description = "Authorization header using the Bearer scheme",
Name = "Authorization",
In = "header"
});
c.DocumentFilter<SwaggerSecurityRequirementsDocumentFilter>();
});
}
在Swagger UI中,单击“授权”按钮并设置令牌值。
结果:
curl -X GET "http://localhost:5000/api/tenants" -H "accept: text/plain" -H "Authorization: Bearer ABCD123456"
答案 3 :(得分:2)
还可以将[FromHeader]属性用于应在自定义标头中发送的网络方法参数(或Model类中的属性)。像这样:
[HttpGet]
public ActionResult Products([FromHeader(Name = "User-Identity")]string userIdentity)
至少它对于ASP.NET Core 2.1和Swashbuckle.AspNetCore 2.5.0正常工作。
答案 4 :(得分:2)
这是ASP.NET Core Web Api / Swashbuckle组合的简单答案,它不需要您注册任何自定义过滤器。你知道第三次是魅力:)。
将以下代码添加到Swagger配置中将导致出现“授权”按钮,从而允许您输入要为所有请求发送的承载令牌。提示时,请不要忘记输入此令牌作为Bearer <your token here>
。
请注意,下面的代码将为所有请求和操作发送令牌,这可能是您想要的,也可能不是您想要的。
services.AddSwaggerGen(c =>
{
//...
c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "Bearer", new string[] { } }
});
//...
}
通过this thread。
答案 5 :(得分:1)
对于那些使用NSwag且需要自定义标题的人:
app.UseSwaggerUi3(typeof(Startup).GetTypeInfo().Assembly, settings =>
{
settings.GeneratorSettings.IsAspNetCore = true;
settings.GeneratorSettings.OperationProcessors.Add(new OperationSecurityScopeProcessor("custom-auth"));
settings.GeneratorSettings.DocumentProcessors.Add(
new SecurityDefinitionAppender("custom-auth", new SwaggerSecurityScheme
{
Type = SwaggerSecuritySchemeType.ApiKey,
Name = "header-name",
Description = "header description",
In = SwaggerSecurityApiKeyLocation.Header
}));
});
}
然后,Swagger UI将包含授权按钮。
答案 6 :(得分:0)
我最终在这里,因为我试图根据我添加到API方法中的[Authentication]
属性,在Swagger UI中有条件地添加标头参数。根据@Corcus在评论中列出的提示,我能够得出我的解决方案,并希望它能帮助其他人。
使用Reflection,它检查嵌套在apiDescription
中的方法是否具有所需的属性(在我的例子中是MyApiKeyAuthenticationAttribute)。如果是,我可以附加我想要的标题参数。
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) {
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
var attributes = ((System.Web.Http.Controllers.ReflectedHttpActionDescriptor)
((apiDescription.ActionDescriptor).ActionBinding.ActionDescriptor)).MethodInfo
.GetCustomAttributes(false);
if(attributes != null && attributes.Any()) {
if(attributes.Where(x => x.GetType()
== typeof(MyApiKeyAuthenticationAttribute)).Any()) {
operation.parameters.Add(new Parameter {
name = "MyApiKey",
@in = "header",
type = "string",
description = "My API Key",
required = true
});
operation.parameters.Add(new Parameter {
name = "EID",
@in = "header",
type = "string",
description = "Employee ID",
required = true
});
}
}
}
答案 7 :(得分:0)
免责声明:此解决方案不是使用Header的。
如果有人正在寻找一种懒惰-懒惰的方式(同样在WebApi中),我建议:
public YourResult Authorize([FromBody]BasicAuthCredentials credentials)
您不是从标题中获取信息,但至少您有一个简单的选择。 您始终可以检查对象是否为null并回退到标头机制。
答案 8 :(得分:0)
Golang / go-swagger示例:https://github.com/go-swagger/go-swagger/issues/1416
// swagger:parameters opid
type XRequestIdHeader struct {
// in: header
// required: true
XRequestId string `json:"X-Request-Id"`
}
...
// swagger:operation POST /endpoint/ opid
// Parameters:
// - $ref: #/parameters/XRequestIDHeader