简体   繁体   English

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

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

I have a ASP.Net WebApi with token based authentication and I want to use swagger to create documentation for this RestApi.我有一个基于令牌的身份验证的 ASP.Net WebApi,我想使用 swagger 为这个 RestApi 创建文档。

The Api has for now only 2 methods, one for requesting a token ie http://localhost:4040/token and the other one is for creating a notification. Api 目前只有两种方法,一种用于请求令牌,即http://localhost:4040/token ,另一种用于创建通知。 The returned bearer token is sent like follows:返回的不记名令牌的发送方式如下:

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;
 }

With swagger I can see the post Notification method, however I can't do a request because I don't have a token and I don't know how to do it in swagger.使用 swagger 我可以看到 post Notification 方法,但是我无法执行请求,因为我没有令牌并且我不知道如何在 swagger 中执行此操作。

I found the solution myself.我自己找到了解决方案。 I would like to share it in case anybody is facing the same problem.如果有人面临同样的问题,我想分享它。 The solution is of 2 steps, first one is to request a token and the next step, is to add the token into the header request.解决方案分为两步,第一步是请求令牌,下一步是将令牌添加到标头请求中。

So the first step:所以第一步:

Customize the frontend to enable post request for requesting a token:自定义前端以启用请求令牌的 post 请求:

在此处输入图片说明

Add a AuthTokenOperation class to enable which inherits the IDcoumentFilter interface and implements the Apply method:添加一个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"
                        },
                    }
                }
            });
        }
    }

And in the SwaggerConfig class in the register method, add this action并在注册方法中的 SwaggerConfig 类中,添加此操作

c.DocumentFilter<AuthTokenOperation>();

to the extension method:到扩展方法:

GlobalConfiguration.Configuration.EnableSwagger

To add the authorization token in the request header:在请求头中添加授权令牌:

在此处输入图片说明

Add this operation class:添加这个操作类:

/// <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"
                });
            }
        }
    }

And in the SwaggerConfig class in the register method, add this action并在注册方法中的 SwaggerConfig 类中,添加此操作

c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();

to the extension method:到扩展方法:

GlobalConfiguration.Configuration.EnableSwagger

Of course in the Authoization field, you need to add: Bearer token_string当然在Authoization字段中,需要添加:Bearer token_string

I just want to add something to the accepted answer that when autorest is used for client generation, the accepted answer is not complete for it misses the some properties.我只想在接受的答案中添加一些内容,即当 autorest 用于客户端生成时,接受的答案不完整,因为它错过了某些属性。

[Fatal]OperationId is required for all operations. [致命]所有操作都需要OperationId。 Please add it for 'post' operation of '/authenticate' path.请为'/authenticate'路径的'post'操作添加它。 Exception: There was an error during code generation when trying to add a client for the REST API Generating client code and adding to project failed Adding REST API client for failed例外:尝试为 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"} } }
                }
            }

you need to add the operationId and responses for autorest to work properly.您需要添加 operationId 和响应以使 autorest 正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 ASP.NET Web 应用程序注销,如果基于 webapi 令牌的身份验证达到其过期时间 - How to logout from ASP.NET web application, if webapi token based authentication reaches it's expire time 使用VS 2013和ADFS 2.0在ASP.NET WebApi中实现基于声明的身份验证 - Implementing Claims based authentication in ASP.NET WebApi using VS 2013 and ADFS 2.0 Asp.Net Core 2.0 Webapi简单身份验证 - Asp.Net Core 2.0 Webapi simple authentication Knockout中的ASP.Net WebAPI Owin身份验证令牌 - ASP.Net WebAPI Owin authentication token in Knockout ASP.NET核心网站使用JWT令牌进行WebApi身份验证 - ASP.NET Core Website to WebApi authentication using JWT token ASP.NET Core 中基于令牌的身份验证 - Token Based Authentication in ASP.NET Core 在 ASP.NET 4.5.2 WebApi 中使用 netstandard 2.0 中间件 - Use netstandard 2.0 middleware into ASP.NET 4.5.2 WebApi 在WebAPI和asp.net核心中使用基于Cookie的身份验证 - Using Cookies based authentication in WebAPI and asp.net core 如何在Azure上托管和部署ASP.Net Core 2.0 WebAPI? - How to Host and Deploy ASP.Net core 2.0 webapi on azure? ASP.NET Identity 2.0中基于令牌的登录逻辑更改 - Token based login logic change in ASP.NET Identity 2.0
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM