簡體   English   中英

如何在基於令牌的身份驗證的 ASP.Net WebAPI 2.0 中使用 Swagger

[英]How to use Swagger in ASP.Net WebAPI 2.0 with token based authentication

我有一個基於令牌的身份驗證的 ASP.Net WebApi,我想使用 swagger 為這個 RestApi 創建文檔。

Api 目前只有兩種方法,一種用於請求令牌,即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;
 }

使用 swagger 我可以看到 post Notification 方法,但是我無法執行請求,因為我沒有令牌並且我不知道如何在 swagger 中執行此操作。

我自己找到了解決方案。 如果有人面臨同樣的問題,我想分享它。 解決方案分為兩步,第一步是請求令牌,下一步是將令牌添加到標頭請求中。

所以第一步:

自定義前端以啟用請求令牌的 post 請求:

在此處輸入圖片說明

添加一個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 類中,添加此操作

c.DocumentFilter<AuthTokenOperation>();

到擴展方法:

GlobalConfiguration.Configuration.EnableSwagger

在請求頭中添加授權令牌:

在此處輸入圖片說明

添加這個操作類:

/// <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 類中,添加此操作

c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();

到擴展方法:

GlobalConfiguration.Configuration.EnableSwagger

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

我只想在接受的答案中添加一些內容,即當 autorest 用於客戶端生成時,接受的答案不完整,因為它錯過了某些屬性。

[致命]所有操作都需要OperationId。 請為'/authenticate'路徑的'post'操作添加它。 例外:嘗試為 REST API 添加客戶端時,代碼生成過程中出現錯誤 生成客戶端代碼並添加到項目失敗 為失敗添加 REST API 客戶端

post = new Operation
            {
                operationId = "Auth_AccessToken",
                tags = new List<string> { "Auth" },
                produces = new List<string>
                {
                    "application/json",
                    "text/json",
                    "application/xml",
                    "text/xml"
                },
                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 = true,
                        @in = "formData"
                    },
                    new Parameter
                    {
                        type = "string",
                        name = "password",
                        required = true,
                        @in = "formData"
                    },
                    new Parameter
                    {
                        type = "string",
                        name = "client_id",
                        required = true,
                        @in = "formData"
                    },
                    new Parameter
                    {
                        type = "string",
                        name = "client_secret",
                        required = true,
                        @in = "formData"
                    }
                },
                responses = new Dictionary<string, Response>
                {
                    {"200", new Response{ description = "OK", schema = new Schema{ type = "object"} } }
                }
            }

您需要添加 operationId 和響應以使 autorest 正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM