首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Swagger :传递自定义授权头

Swagger :传递自定义授权头
EN

Stack Overflow用户
提问于 2016-08-11 21:10:33
回答 4查看 22.1K关注 0票数 14

我在一个ASP.NET Web上使用Swashbuckle和Swagger。我正在设法通过Swagger传递包含Bearer令牌的授权头。我一直在搜索,但是所有的答案似乎都指向链接。

但是,这假设头的内容是预先知道的。我真的需要一种在Swagger中改变标题的方法(就在点击“试试看!”)按钮),因为Bearer令牌每小时过期一次。类似于Postman允许您添加标题的方式。

这似乎是一个可笑的简单问题,但答案是什么呢?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-08-12 10:33:13

我们在项目中遇到了同样的问题。我还想将标题参数添加到Swagger网站中。我们就是这样做的:

1.在每次构建Swagger时,在每个API操作上执行OperationFilter类 OperationFilters。根据您的代码,操作将根据您的过滤器进行检查。在本例中,我们为每个操作设置所需的标头参数,但在具有AllowAnonymous属性的操作中使其成为可选参数。

代码语言:javascript
运行
复制
    public class AddAuthorizationHeader : IOperationFilter
    {
        /// <summary>
        /// Adds an authorization header to the given operation in Swagger.
        /// </summary>
        /// <param name="operation">The Swashbuckle operation.</param>
        /// <param name="schemaRegistry">The Swashbuckle schema registry.</param>
        /// <param name="apiDescription">The Swashbuckle api description.</param>
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation == null) return;

            if (operation.parameters == null)
            {
                operation.parameters = new List<Parameter>();
            }

            var parameter = new Parameter
            {
                description = "The authorization token",
                @in = "header",
                name = "Authorization",
                required = true,
                type = "string"
            };

            if (apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
            {
                parameter.required = false;
            }

            operation.parameters.Add(parameter);
        }
    }

2.告诉Swagger在SwaggerConfig中使用这个OperationFilter,只需添加操作过滤器,如下所示:

代码语言:javascript
运行
复制
    c.OperationFilter<AddAuthorizationHeader>();

希望这能帮到你!

票数 25
EN

Stack Overflow用户

发布于 2017-07-05 13:23:16

创建一个实现IOperationFilter的新操作过滤器。

代码语言:javascript
运行
复制
public class AuthorizationHeaderOperationFilter : IOperationFilter
{
    /// <summary>
    /// Adds an authorization header to the given operation in Swagger.
    /// </summary>
    /// <param name="operation">The Swashbuckle operation.</param>
    /// <param name="context">The Swashbuckle operation filter context.</param>
    public void Apply(Operation operation, OperationFilterContext context)
    {
        if (operation.Parameters == null)
        {
            operation.Parameters = new List<IParameter>();
        }

        var authorizeAttributes = context.ApiDescription
            .ControllerAttributes()
            .Union(context.ApiDescription.ActionAttributes())
            .OfType<AuthorizeAttribute>();
        var allowAnonymousAttributes = context.ApiDescription.ActionAttributes().OfType<AllowAnonymousAttribute>();

        if (!authorizeAttributes.Any() && !allowAnonymousAttributes.Any())
        {
            return;
        }

        var parameter = new NonBodyParameter
        {
            Name = "Authorization",
            In = "header",
            Description = "The bearer token",
            Required = true,
            Type = "string"
        };

        operation.Parameters.Add(parameter);
    }
}

Startup.cs文件中配置服务。

代码语言:javascript
运行
复制
        services.ConfigureSwaggerGen(options =>
        {
            options.OperationFilter<AuthorizationHeaderOperationFilter>();
        });
票数 6
EN

Stack Overflow用户

发布于 2016-08-11 21:52:44

根据收集Authorization头的方式以及是否希望代码处理所有内容,或者如果您希望用户能够输入他们想要的任何Authorization头,您可以使用不同的方式。

当我第一次尝试这样做时,我能够在每个端点的参数字段区域中显示一个Authorization头文本,用户可以在其中输入一个Authorization头,但这不是我想要的。

在我的情况下,我必须用用户的cookie向/token端点发送一个请求,以获得有效的Authorization令牌。所以我做了一些事情来达到这个目的。

首先,在SwaggerConfig.cs中,我取消了注释的c.BasicAuth()以将基本的auth方案输入到API模式中,我还插入了一个自定义的index.html页面,其中插入了一个AJAX请求,以便使用用户的cookie (下面显示的index.html代码)获取Authorization令牌:

代码语言:javascript
运行
复制
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");

                    ...
                });
}

然后,head 这里下载swashbuckle index.html,我们将对其进行定制,以插入Authorization头。

下面我只使用一个有效的cookie对我的/token端点进行AJAX调用,获取Authorization令牌,并将它交给swagger用于window.swaggerUi.api.clientAuthorizations.add()

代码语言:javascript
运行
复制
...

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头。在这种情况下,这很容易。我用了帖子。只需创建以下类来完成这项工作:

代码语言:javascript
运行
复制
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中,如下所示:

代码语言:javascript
运行
复制
...
c.OperationFilter<AddRequiredHeaderParameter>();
...
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38906224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档