zoukankan      html  css  js  c++  java
  • 重新拾取: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

  • 相关阅读:
    c#基础练习
    一款很厉害的死循环代码
    文字变色逐个出现的特效源码
    IOS开发之UILabel动态高度设置方法
    慎重选择容器类型
    Mac下显示隐藏文件 以及修改 hosts文件内容
    SharePoint 如何使自己的网页自动跳转
    位置和地图:地图的使用
    谈话Java在ThreadLocal理解类
    Android 滑动界面实现---Scroller类别 从源代码和开发文档了解(让你的移动布局)
  • 原文地址:https://www.cnblogs.com/79039535/p/9289548.html
Copyright © 2011-2022 走看看