园子里已经有很多.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