重新拾取: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

转载于:https://www.cnblogs.com/79039535/p/9289548.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值