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

ala*_*egh 10 c# asp.net-web-api swagger bearer-token

我有一个基于令牌的身份验证的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;
 }
Run Code Online (Sandbox Code Playgroud)

随心所欲,我可以看到帖子通知方法,但我不能做一个请求,因为我没有令牌,我不知道如何在招摇中做到这一点.任何帮助都非常感谢

非常感谢!

ala*_*egh 28

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

所以第一步:

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

在此输入图像描述

添加一个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"
                        },
                    }
                }
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

c.DocumentFilter<AuthTokenOperation>();
Run Code Online (Sandbox Code Playgroud)

到扩展方法:

GlobalConfiguration.Configuration.EnableSwagger
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

添加此操作类:

/// <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"
                });
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();
Run Code Online (Sandbox Code Playgroud)

到扩展方法:

GlobalConfiguration.Configuration.EnableSwagger
Run Code Online (Sandbox Code Playgroud)

当然,在Authoization字段中,您需要添加:Bearer token_string

  • Tim Corey 在他的 YouTube 视频教程之一中详细介绍了这种方法(归因于此答案)。链接:https://www.youtube.com/watch?v=zQRgB6nasUc (3认同)