重新拾取:ASP.NET Core WebApi 使用Swagger支持授权认证

园子里已经有很多Swagger的文章,对于使用授权的缺蛮少的。

public static class SwaggerServiceExtensions
{
        public static IServiceCollection AddSwaggerCustom(this IServiceCollection services, IConfiguration configuration)
        {
            //注册SwaggerAPI文档服务
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Title = configuration["GlobalSettings:ProjectName"],
                    Version = "v1",
                });
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "请输入带有Bearer的Token",
                    Name = "Authorization",
                    In = "header",
                    Type = "apiKey"
                });
                //Json Token认证方式,此方式为全局添加
                options.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                {
                    { "Bearer", Enumerable.Empty<string>() }
                });
          //获取应用程序根目录路径,官方写法
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                //linux环境下获取路径没有问题
                //var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
                //使用更简洁的AppContext.BaseDirectory、linux下也没问题
                //var basePath = AppContext.BaseDirectory;
                //设置Swagger注释  需要 右键项目 -> 生成  -> 输出 -> 勾选XML文档文件 才会产生XML文件
                var xmlPath = Path.Combine(basePath, "SexyBook.ClientApi.xml");
                if (System.IO.File.Exists(xmlPath))
                    options.IncludeXmlComments(xmlPath);
            });

            return services;
        }

        public static IApplicationBuilder UseSwaggerCustom(this IApplicationBuilder builder, IConfiguration configuration)
        {
            //启用Swagger
            builder.UseSwagger();
            //启用SwaggerUI
            builder.UseSwaggerUI(options =>
            {
                //文档终结点
                options.SwaggerEndpoint("/swagger/v1/swagger.json", $"{configuration["GlobalSettings:ProjectName"]} API V1");
                //文档标题
                options.DocumentTitle = configuration["GlobalSettings:ProjectName"];
                //页面API文档格式 Full=全部展开, List=只展开列表, None=都不展开
                options.DocExpansion(DocExpansion.List);
            });
            return builder;
        }
 }

此方式乃全局应用,每个接口服务都能直接应用上Token,当然如果你不喜欢可以选择 实现IOperationFilter接口

public class SecurityRequirementsOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        var requiredScopes = context.MethodInfo
            .GetCustomAttributes(true)
            .OfType<AuthorizeAttribute>()
            .Select(attr => attr.Policy)
            .Distinct();

        if (requiredScopes.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>>>();
            operation.Security.Add(new Dictionary<string, IEnumerable<string>>
            {
                { "oauth2", requiredScopes }
            });
        }
    }
}

参考文章

https://ppolyzos.com/2017/10/30/add-jwt-bearer-authorization-to-swagger-and-asp-net-core/

http://www.cnblogs.com/NuoYer/p/8252023.html

https://www.cnblogs.com/yilezhu/p/9241261.html

https://www.cnblogs.com/yanbigfeg/p/9232844.html

https://github.com/domaindrivendev/Swashbuckle.AspNetCore

猜你喜欢

转载自www.cnblogs.com/79039535/p/9289548.html