ASP Net Core 2.2 仅向需要授权的方法添加储物柜图标 - Swagger UI [英] ASP Net Core 2.2 add locker icon only to methods that require authorization - Swagger UI

查看:17
本文介绍了ASP Net Core 2.2 仅向需要授权的方法添加储物柜图标 - Swagger UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • ASP 网络核心 Web API - 2.2
  • Swashbuckle.AspNetCore - 4.0.1

我在我的 Web API 项目中实现了 swagger.我在需要它的方法上使用带有 [Authorize] 属性的 JWT 授权.

I have implemented swagger in my Web API project. And I am using JWT authorization with [Authorize] attribute on the methods that require it.

所以我想要一种能够发送需要授权的请求的简单方法.在我的 ConfigureServices 类中,我添加了以下逻辑.

So I wanted an easy way to be able to send requests that require authorization. In my ConfigureServices class, I've added the following logic.

services.AddSwaggerGen(c =>
{

    // Other swagger options

    c.AddSecurityDefinition("Bearer", new ApiKeyScheme
    {
        In = "header",
        Description = "Please enter into field the word 'Bearer' following by space and your JWT token",
        Name = "Authorization",
        Type = "apiKey"
    });
    c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
    {
        { "Bearer", Enumerable.Empty<string>() },
    });

    // Other swagger options
});

它的作用如下:
它在 swagger 中添加了一个新按钮 - 授权.

What this does is the following:
It adds one new button in swagger - Authorize.

问题是,它还在每个方法旁边添加了一个打开"储物柜图标.尽管如此,其中一些需要授权.

The problem is, it also adds an "open" locker icon, next to every method. Even though, some of them require authorization.

当我使用授权按钮成功授权时(它基本上为每个请求添加了标头授权),我在所有请求上都会收到一个关闭"的储物柜.

And when I authorize successfully using the Authorize button (It basically adds header Authorization to each request), I receive a "closed" locker on all of them.

我知道这可能是需要的功能,用于指示将通过请求发送授权令牌.我想要一种方法来显示哪些方法需要授权,哪些不需要.

I know this is probably desired functionality to indicate that an Authorization token will be sent via the request. I want a way to show which methods require authorization and which don't.

例如,匿名方法的打开"锁柜和具有 [Authorize] 属性的方法的关闭"锁柜.

For instance, the "open" locker for anonymous methods and "closed" locker for methods that have [Authorize] attribute on them.

它可以是一个附加图标,在此旁边或修改此图标的行为,没问题.我怎样才能做到这一点?

It could be an additional icon, next to this or to modify the behaviour of this one, no problem. How can I achieve this?

我相信一个可能的解决方案是创建一个 OperationFilter 并检查所有方法,并仅将某物"附加到那些具有 [Authorize] 属性的方法上.这是最好的解决方案吗?如果是这样,您将如何实施?

I believe a possible solution is to make an OperationFilter and go through all methods and attach "something" only to those that have [Authorize] attribute on them. Is this the best solution? If so, how would you implement it?

推荐答案

自从我问这个问题一个多月以来.这是我如何做到的.

Since it went more than a month since I asked this one. Here is how I did it.

我从 Startup.cs 中删除了以下代码:

I deleted the following code from Startup.cs:

c.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
    In = "header",
    Description = "Please enter into field the word 'Bearer' following by space and your JWT token",
    Name = "Authorization",
    Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
    { "Bearer", Enumerable.Empty<string>() },
});

我添加了以下内容:

c.OperationFilter<AddAuthHeaderOperationFilter>();

当然还有 AddAuthHeaderOperationFilter.cs:

    public class AddAuthHeaderOperationFilter : IOperationFilter
    {
        private readonly IHttpContextAccessor httpContextAccessor;

        public AddAuthHeaderOperationFilter(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        public void Apply(Operation operation, OperationFilterContext context)
        {
            var filterDescriptor = context.ApiDescription.ActionDescriptor.FilterDescriptors;
            var isAuthorized = filterDescriptor.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
            var allowAnonymous = filterDescriptor.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 = "JWT access token",
                    Required = true,
                    Type = "string",
                    //Default = $"Bearer {token}"
                });

                operation.Responses.Add("401", new Response { Description = "Unauthorized" });
                operation.Responses.Add("403", new Response { Description = "Forbidden" });

                operation.Security = new List<IDictionary<string, IEnumerable<string>>>();

                //Add JWT bearer type
                operation.Security.Add(new Dictionary<string, IEnumerable<string>>
                {
                    { "Bearer", new string[] { } }
                });
            }
        }
    }

简而言之,这个 OperationFilter 类只将储物柜图标添加到需要授权的方法中.储物柜总是打开的.所以不是完美的解决方案,但现在还可以.

Shortly, this OperationFilter class only adds the locker icon to methods that require Authorization. The locker is always Opened though. So not the perfect solution, but for now is ok.

外观如下:

注意:因此,如果您想测试 API,您首先要获得一个令牌,然后在需要的地方填写它.

Note: So if you want to test the API, you first get a token and then fill it where needed.

这篇关于ASP Net Core 2.2 仅向需要授权的方法添加储物柜图标 - Swagger UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆