根据您收集Authorization 标头的方式以及您是否希望代码处理所有内容,或者您是否希望用户能够输入他们想要的任何Authorization 标头,您可以采用不同的方式进行操作。
当我第一次尝试这个时,我能够在每个端点的参数字段区域中显示 Authorization 标头文本,用户可以在其中键入 Authorization 标头,但这不是我想要的。
在我的情况下,我必须使用用户的 cookie 向 /token 端点发送请求,以获得有效的 Authorization 令牌。所以我做了很多事情来实现这一点。
首先在SwaggerConfig.cs 中,我取消了c.BasicAuth() 的注释以将基本身份验证方案添加到API 架构中,并且我还注入了一个自定义index.html 页面,在该页面中我插入了一个AJAX 请求以获取Authorization 令牌,使用用户的 cookie(index.html 代码如下所示):
public static void Register() {
System.Reflection.Assembly thisAssembly = typeof(SwaggerConfig).Assembly;
System.Web.Http.GlobalConfiguration.Configuration
.EnableSwagger(c => {
...
c.BasicAuth("basic").Description("Bearer Token Authentication");
...
})
.EnableSwaggerUi(c => {
...
c.CustomAsset("index", thisAssembly, "YourNamespace.index.html");
...
});
}
然后前往here 下载swashbuckle index.html,我们将自定义它以插入Authorization 标头。
下面我简单地使用有效的 cookie 对我的 /token 端点进行 AJAX 调用,获取 Authorization 令牌,并将其提供给 swagger 以与 window.swaggerUi.api.clientAuthorizations.add() 一起使用:
...
function log() {
if ('console' in window) {
console.log.apply(console, arguments);
}
}
$.ajax({
url: url + 'token'
, type: 'POST'
, data: { 'grant_type': 'CustomCookie' }
, contentType: 'application/x-www-form-urlencoded'
, async: true
, timeout: 60000
, cache: false
, success: function(response) {
console.log('Token: ' + response['token_type'] + ' ' + response['access_token']);
window.swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", response['token_type'] + ' ' + response['access_token'], "header"));
}
, error: function(request, status, error) {
console.log('Status: ' + status + '. Error: ' + error + '.');
}
});
我从 AJAX 调用中删除了一些内容以使其更简单,显然您的实现可能会有所不同,具体取决于您收集Authorization 令牌和内容的方式,但这给了您一个想法。如果您有任何具体问题或疑问,请告诉我。
*编辑:没有注意到您实际上确实希望用户输入他们的Authorization 标头。在这种情况下,这很容易。我使用了this 帖子。只需创建以下类来完成这项工作:
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 = "Foo-Header",
@in = "header",
type = "string",
required = true
});
}
}
然后像这样将课程添加到我的SwaggerConfig:
...
c.OperationFilter<AddRequiredHeaderParameter>();
...