如何在具有基于令牌的身份验证的ASP.Net WebAPI 2.0中使用Swagger

问题描述 投票:11回答:2

我有一个具有基于令牌的身份验证的ASP.Net WebApi,并且我想使用swagger为该RestApi创建文档。

Api目前只有2种方法,一种用于请求令牌,即http://localhost:4040/token,另一种用于创建通知。返回的承载令牌的发送方式如下:

using (var client = new HttpClient())
{
    // setup client
    client.BaseAddress = new Uri("http://localhost:4040");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

    var serializedNotification = new JavaScriptSerializer().Serialize(notification);
    var stringContent = new StringContent(serializedNotification, Encoding.UTF8, "application/json");

    var response = await client.PostAsync("api/Notification", stringContent);
    response.EnsureSuccessStatusCode();

    // return URI of the created resource.
    return response.Headers.Location;
 }

有了招摇,我可以看到post Notification方法,但是我没有请求,因为我没有令牌,也不知道如何用招摇。

c# asp.net-web-api swagger bearer-token
2个回答
31
投票

我自己找到了解决方案。如果有人遇到同样的问题,我想分享一下。解决方案包括2个步骤,第一步是请求令牌,下一步是将令牌添加到标头请求中。

因此第一步:

自定义前端以启用发布请求以请求令牌:

enter image description here

添加要启用的AuthTokenOperation类,该类继承IDcoumentFilter接口并实现Apply方法:

public class AuthTokenOperation : IDocumentFilter
    {
        /// <summary>
        /// Apply custom operation.
        /// </summary>
        /// <param name="swaggerDoc">The swagger document.</param>
        /// <param name="schemaRegistry">The schema registry.</param>
        /// <param name="apiExplorer">The api explorer.</param>
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            swaggerDoc.paths.Add("/token", new PathItem
            {
                post = new Operation
                {
                    tags = new List<string> { "Auth"},
                    consumes = new List<string>
                    {
                        "application/x-www-form-urlencoded"
                    },
                    parameters = new List<Parameter>
                    {
                        new Parameter
                        {
                            type = "string",
                            name = "grant_type",
                            required = true,
                            @in = "formData"
                        },
                        new Parameter
                        {
                            type = "string",
                            name = "username",
                            required = false,
                            @in = "formData"
                        },
                        new Parameter
                        {
                            type = "string",
                            name = "password",
                            required = false,
                            @in = "formData"
                        },
                    }
                }
            });
        }
    }

并且在SwaggerConfig类的register方法中,添加此操作

c.DocumentFilter<AuthTokenOperation>();

至扩展方法:

GlobalConfiguration.Configuration.EnableSwagger

要在请求标头中添加授权令牌:

enter image description here

添加此操作类:

/// <summary>
    /// The class to add the authorization header.
    /// </summary>
    public class AddAuthorizationHeaderParameterOperationFilter : IOperationFilter
    {
        /// <summary>
        /// Applies the operation filter.
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="schemaRegistry"></param>
        /// <param name="apiDescription"></param>
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.parameters != null)
            {
                operation.parameters.Add(new Parameter
                {
                    name = "Authorization",
                    @in = "header",
                    description = "access token",
                    required = false,
                    type = "string"
                });
            }
        }
    }

并且在SwaggerConfig类的register方法中,添加此操作

c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();

至扩展方法:

GlobalConfiguration.Configuration.EnableSwagger

当然,在Authoization字段中,需要添加:不记名token_string


0
投票

感谢您的解决方案。它在firefox中完美运行,但是Response Body在其他浏览器中显示“无内容”。

© www.soinside.com 2019 - 2024. All rights reserved.