c# - 如何在基于 token 的身份验证的 ASP.Net WebAPI 2.0 中使用 Swagger

标签 c# asp.net-web-api swagger bearer-token

我有一个带有基于 token 的身份验证的 ASP.Net WebApi,我想使用 swagger 为这个 RestApi 创建文档。

Api 目前只有 2 种方法,一种用于请求 token ,即 http://localhost:4040/token,另一种用于创建通知。返回的不记名 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;
 }

有了 swagger,我可以看到 post Notification 方法,但是我无法发出请求,因为我没有 token ,而且我不知道如何在 swagger 中执行此操作。

最佳答案

我自己找到了解决方案。我想分享它以防有人遇到同样的问题。解决方案分为两步,第一步是请求 token ,下一步是将 token 添加到 header 请求中。

所以第一步:

自定义前端以启用请求 token 的post请求:

enter image description here

添加AuthTokenOperation类启用,继承IDcoumentFilter接口(interface)并实现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方法中,添加这个action

c.DocumentFilter<AuthTokenOperation>();

扩展方法:

GlobalConfiguration.Configuration.EnableSwagger

在请求 header 中添加授权 token :

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方法中,添加这个action

c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();

扩展方法:

GlobalConfiguration.Configuration.EnableSwagger

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

关于c# - 如何在基于 token 的身份验证的 ASP.Net WebAPI 2.0 中使用 Swagger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51117655/

相关文章:

C#,TextBox '&' char 更改为 amp;

c# - 如何使用自签名证书使用私钥创建签名的 x509certificate

c# - 没有堆栈跟踪的错误详细信息

c# - 从 asp.net core 高效地发送文件

c# - .NET Web API 异常错误详细信息

java - Swagger DefaultGenerator 类未找到?

jwt - 在 Swagger UI 中,如何从 "anonymous"方法中删除挂锁图标?

c# - C# 中的 Convert.ToDouble 和 Double.Parse

c# - 如何使用匿名方法设置线程名称?

spring-mvc - Spring Boot 和 Swagger 2 : UnsatisfiedDependencyException - Repository tests not working