四、Swagger验证(非全局token)

一、非全局token

 看起来全部是token验证,无法区分那个方法是需要token验证的和非token验证的,很混乱。

 选择 实现IOperationFilter接口

 代码如下:

using Microsoft.AspNetCore.Authorization;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace ZanLveCore
{
    public class SwaggerOperationFilter : IOperationFilter
    {
        public void Apply(Swashbuckle.AspNetCore.Swagger.Operation operation, OperationFilterContext context)
        {
            operation.Parameters = operation.Parameters ?? new List<IParameter>();
            var info = context.MethodInfo;
            context.ApiDescription.TryGetMethodInfo(out info);
            try
            {
                Attribute attribute = info.GetCustomAttribute(typeof(AuthorizeAttribute));
                if (attribute != null)
                {
                    operation.Parameters.Add(new BodyParameter
                    {
                        Name = "Authorization",
                        @In = "header",
                        Description = "access_token",
                        Required = true
                    });
                }

            }
            catch
            { }
        }

    }
}

接下来调用 options.OperationFilter<SwaggerOperationFilter>(); 就好啦

 效果如图:

Authorization 的

二、core3.1 全局小锁

只是检查contorller的authroize注解。有就在swagger文档加锁。没有就不加。

代码如下:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.JsonPatch.Operations;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Web.Api.Server.Swagger
{
    public class AuthResponsesOperationFilter : IOperationFilter
    {

        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
                .Union(context.MethodInfo.GetCustomAttributes(true))
                .OfType<AuthorizeAttribute>();

            if (authAttributes.Any())
            {
                operation.Responses.Add("401", new OpenApiResponse { Description = "未经许可的访问(Unauthorized)" });
                operation.Responses.Add("403", new OpenApiResponse { Description = "禁止访问(Forbidden)" });

                var BearerScheme = new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
                };
                operation.Security = new List<OpenApiSecurityRequirement>
                    {
                        new OpenApiSecurityRequirement
                        {
                            [BearerScheme] = new List<string>()
                        }
                    };
            }
        }
    }
}

引用

 三、core 2.1 全局小锁

只是检查contorller的authroize注解。有就在swagger文档加锁。没有就不加。

using Microsoft.AspNetCore.Authorization;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;
using System.Linq;

namespace ZanLveCore
{
    public class AuthResponsesOperationFilter : IOperationFilter
    {
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
                .Union(context.MethodInfo.GetCustomAttributes(true))
                .OfType<AuthorizeAttribute>();

            if (authAttributes.Any())
            {
                operation.Responses.Add("401", new Response { Description = "未经许可的访问(Unauthorized)" });
                operation.Responses.Add("403", new Response { Description = "禁止访问(Forbidden)" });

                operation.Security = new List<IDictionary<string, IEnumerable<string>>>
                    {
                        new Dictionary<string, IEnumerable<string>>
                        {
                            { "Bearer", Enumerable.Empty<string>() }
                        }
                    };
            }
        }
    }
}

效果:

 注意:虽然ui小锁实现,但是点击没触发,需要更改添加上支持Swagger验证

 对应

 代码如下:

                //添加一个必须的全局安全信息
                /*var security = new Dictionary<string, IEnumerable<string>> { { "ZanLveCore", new string[] { } }, };
                 options.AddSecurityRequirement(security);*/
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                 {
                     Description = "JWT授权(数据将在请求头中进行传输) 在下方输入Bearer {token} 即可,注意两者之间有空格",
                     Name = "Authorization",//jwt默认的参数名称
                     In = "header",//jwt默认存放Authorization信息的位置(请求头中)
                     Type = "apiKey"
                 });
                // Token绑定到ConfigureServices

最好将Bearer更改ZanLveCore(授权解决方案名)

原文地址:https://www.cnblogs.com/fger/p/12095707.html