Use JWT (Authorization: Bearer) in Swagger in ASP.NET Core

前端 未结 7 662
闹比i
闹比i 2020-12-02 15:37

I\'m creating a REST api in ASP.NET Core 1.0. I was using Swagger to test but now I added JWT authorization for some routes. (with UseJwtBearerAuthentication)

7条回答
  •  天命终不由人
    2020-12-02 16:04

    I struggled with the same problem and found a working solution in this blogpost: http://blog.sluijsveld.com/28/01/2016/CustomSwaggerUIField

    It comes down to adding this in your configurationoptions

    services.ConfigureSwaggerGen(options =>
    {
       options.OperationFilter();
    });
    

    and the code for the operationfilter

    public class AuthorizationHeaderParameterOperationFilter : IOperationFilter
    {
       public void Apply(Operation operation, OperationFilterContext context)
       {
          var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors;
          var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
          var allowAnonymous = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);
    
          if (isAuthorized && !allowAnonymous)
          {
              if (operation.Parameters == null)
                 operation.Parameters = new List();
    
              operation.Parameters.Add(new NonBodyParameter
              {                    
                 Name = "Authorization",
                 In = "header",
                 Description = "access token",
                 Required = true,
                 Type = "string"
             });
          }
       }
    }
    

    Then you will see an extra Authorization TextBox in your swagger where you can add your token in the format 'Bearer {jwttoken}' and you should be authorized in your swagger requests.

提交回复
热议问题