在 ASP.NET Core 的 Swagger 中使用 JWT(授权:Bearer)

Use JWT (Authorization: Bearer) in Swagger in ASP.NET Core(在 ASP.NET Core 的 Swagger 中使用 JWT(授权:Bearer))
本文介绍了在 ASP.NET Core 的 Swagger 中使用 JWT(授权:Bearer)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在 ASP.NET Core 1.0 中创建一个 REST api.我使用 Swagger 进行测试,但现在我为某些路由添加了 JWT 授权.(使用 UseJwtBearerAuthentication)

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)

是否可以修改 Swagger 请求的标头,以便可以测试具有 [Authorize] 属性的路由?

Is it possible to modify the header of the Swagger requests so the routes with the [Authorize] attribute can be tested?

推荐答案

我遇到了同样的问题,并在这篇博文中找到了一个可行的解决方案:http://blog.sluijsveld.com/28/01/2016/CustomSwaggerUIField

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<AuthorizationHeaderParameterOperationFilter>();
});

以及操作过滤器的代码

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<IParameter>();

          operation.Parameters.Add(new NonBodyParameter
          {                    
             Name = "Authorization",
             In = "header",
             Description = "access token",
             Required = true,
             Type = "string"
         });
      }
   }
}

然后你会在你的 swagger 中看到一个额外的 Authorization TextBox,你可以在其中以Bearer {jwttoken}"格式添加你的令牌,并且你应该在你的 swagger 请求中获得授权.

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.

这篇关于在 ASP.NET Core 的 Swagger 中使用 JWT(授权:Bearer)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Custom Error Queue Name when using EasyNetQ for RabbitMQ?(使用 EasyNetQ for RabbitMQ 时自定义错误队列名称?)
How to generate password_hash for RabbitMQ Management HTTP API(如何为 RabbitMQ 管理 HTTP API 生成密码哈希)
Rabbitmq Ack or Nack, leaving messages on the queue(Rabbitmq Ack 或 Nack,将消息留在队列中)
Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Specify Publish timeouts in mass transit(指定公共交通中的发布超时)
RabbitMQ asynchronous support(RabbitMQ 异步支持)