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


    园子里已经有很多.NET Core 集成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 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>(); 就好啦

    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",
                    });
                    //使用过滤器单独对某些API接口实施认证
                    options.OperationFilter<SwaggerOperationFilter>();
    
                    //获取应用程序根目录路径,官方写法
                    var basePath = PlatformServices.Default.Application.ApplicationBasePath;//设置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;
            }
        }

    参考文章

    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

  • 相关阅读:
    就为了一个原子操作,其他CPU核心罢工了
    浅谈JVM和垃圾回收
    简单了解一下K8S,并搭建自己的集群
    WebAssembly完全入门——了解wasm的前世今身
    【简单了解系列】从基础的使用来深挖HashMap
    【俗话说】换个角度理解TCP的三次握手和四次挥手
    两分钟让你明白Go中如何继承
    游戏服务器和Web服务器的区别
    Go中使用seed得到相同随机数的问题
    从web到游戏,走出舒适区
  • 原文地址:https://www.cnblogs.com/79039535/p/9289548.html
Copyright © 2020-2023  润新知