從新拾取:ASP.NET Core WebApi 使用Swagger支持受權認證

園子裏已經有不少.NET Core 集成Swagger的文章,但對於使用受權的介紹蠻少的。html

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接口linux

 

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>(); 就好啦git

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;
        }
    }

 

 

參考文章github

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

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

http://www.javashuo.com/article/p-xlcnpzoq-gy.htmldom

http://www.javashuo.com/article/p-qbylylet-ha.htmlui

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

相關文章
相關標籤/搜索