園子里已經有很多.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
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。