欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Swagger如何访问Ocelot中带权限验证的API

程序员文章站 2022-03-21 21:31:31
Swagger作为WebAPI的文档工具,广为人知,Swagger对asp.net core的支持也几近完美,这篇博文不是对asp.net core中使用Swagger作介绍,因为社区博客作了详细说明。 今天主要说一下Swagger在Ocelot网关权限验证模式下的访问,以及Swagger请求应答的... ......

先亮源代码:https://github.com/axzxs2001/Asp.NetCoreExperiment/tree/master/Asp.NetCoreExperiment/SwaggerDemo

这篇博文不是对asp.net core中使用Swagger作介绍,因为社区博客作了详细说明。

今天主要说一下Swagger在Ocelot网关权限验证模式下的访问,以及Swagger请求应答的数据格式。

首先创建四个项目:

SwaggerOcelot:asp.net core web api类型,api网关项目

SwaggerAuthorize:asp.net core web api类型,用户验证项目

SwaggerAPI01:asp.net core web api类型,api 1项目

SWaggerAPI02:asp.net core web api类型,api 2项目

首先在四个项目中添加基于Jwt的Toekn认证,参见

再在四个项目Nuget中引入Swashbuckle.AspNetCore,我的Demo中用的是2.5.0,再分别配置Swagger

 SwaggerAuthorize  Starup.cs配置

 1 public void ConfigureServices(IServiceCollection services)
 2 {
 3     services.AddTokenJwtAuthorize();
 4     services.AddMvc()
 5             .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
 6     services.AddSwaggerGen(options =>
 7     {
 8         options.SwaggerDoc("SwaggerAuthorize", new Info { Title = "Authorize", Version = "v1", Contact = new Contact { Email = "285130205@qq.com", Name = "Authorize", Url = "http://0.0.0.0" }, Description = "Authorize项目" });
 9         var basePath = PlatformServices.Default.Application.ApplicationBasePath;
10         var xmlPath = Path.Combine(basePath, "SwaggerAuthorize.xml");
11         options.IncludeXmlComments(xmlPath);
12     });
13 }
14 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
15 {
16     if (env.IsDevelopment())
17     {
18         app.UseDeveloperExceptionPage();
19     }
20  
21     app.UseMvc()
22         .UseSwagger(options =>
23         {
24             options.RouteTemplate = "{documentName}/swagger.json";
25         })
26         .UseSwaggerUI(options =>
27         {
28             options.SwaggerEndpoint("/SwaggerAuthorize/swagger.json", "Authorize");
29         });
30 }

SwaggerAPI01,SwaggerAPI02类似,Starup.cs配置,其中让Swagger支付Token验证,就是要在这部分添加Swagger配置

 1 public void ConfigureServices(IServiceCollection services)
 2 {
 3     services.AddApiJwtAuthorize((context) =>
 4     {
 5         return true;
 6     });
 7  
 8     services.AddSwaggerGen(options =>
 9     {
10         options.SwaggerDoc("SwaggerAPI01", new Info { Title = "API01", Version = "v1", Contact = new Contact { Email = "285130205@qq.com", Name = "API01", Url = "http://0.0.0.0" }, Description = "API01项目" });
11         var basePath = PlatformServices.Default.Application.ApplicationBasePath;
12         var xmlPath = Path.Combine(basePath, "SwaggerAPI01.xml");
13         options.IncludeXmlComments(xmlPath);
14  
15         //这里是给Swagger添加验证的部分
16         options.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description = "请输入带有Bearer的Token", Name = "Authorization", Type = "apiKey" });
17         options.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
18             {
19                 "Bearer",
20                 Enumerable.Empty<string>()
21             }
22         });
23     });
24     services
25         .AddMvc()
26         .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
27 }
28  
29 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
30 {
31     app.UseMvc()
32         .UseSwagger(options =>
33         {
34             options.RouteTemplate = "{documentName}/swagger.json";
35         })
36         .UseSwaggerUI(options =>
37         {
38             options.SwaggerEndpoint("/SwaggerAPI01/swagger.json", "API01");
39         });
40 }

SwaggerOcelot,Starup.cs配置

 1 public void ConfigureServices(IServiceCollection services)
 2 {
 3     services.AddOcelotJwtAuthorize();
 4     //注入Ocelot
 5     services.AddOcelot(Configuration);
 6     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
 7  
 8     services.AddSwaggerGen(options =>
 9     {
10         options.SwaggerDoc("ApiGateway", new Info { Title = "网关服务", Version = "v1", Contact = new Contact { Email = "285130205@qq.com", Name = "SwaggerOcelot", Url = "http://10.10.10.10" }, Description = "网关平台" });
11     });
12 }
13  
14 public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
15 {
16     if (env.IsDevelopment())
17     {
18         app.UseDeveloperExceptionPage();
19     }
20  
21     var apis = new Dictionary<string, string>(
22         new KeyValuePair<string, string>[] {
23             KeyValuePair.Create("SwaggerAuthorize", "Authorize"),
24             KeyValuePair.Create("SwaggerAPI01", "API01"),
25             KeyValuePair.Create("SwaggerAPI02", "API02")
26         });
27  
28     app.UseMvc()
29        .UseSwagger()
30        .UseSwaggerUI(options =>
31        {
32            apis.Keys.ToList().ForEach(key =>
33            {
34                options.SwaggerEndpoint($"/{key}/swagger.json", $"{apis[key]} -【{key}】");
35            });
36            options.DocumentTitle = "Swagger测试平台";
37        });
38     await app.UseOcelot();
39 }

接下来,为Swagger访问Web API项目,添加请求返回格式,默认状况下,Swagger是支持Json的,下来添加支持XML格式

第一步,添加支持XML格式

1 services.AddMvc()
2                   .AddXmlSerializerFormatters() //设置支持XML格式输入输出
3                   .AddJsonOptions(op => op.SerializerSettings.ContractResolver = new DefaultContractResolver())//大小写不转换
4                   .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

第二步,在对应的Action添加ProducesResponseType特性,为转换作支持

1 [HttpGet("{id}")]
2 [ProducesResponseType(typeof(API01Model), 200)]
3 public ActionResult<API01Model> Get(int id)
4 {
5     return new API01Model { ID = 1, IsSure = true, Price = 2.3m, Describe = "test1" };
6 }

运行效果:

先看登录

Swagger如何访问Ocelot中带权限验证的API

 

再看api访问

Swagger如何访问Ocelot中带权限验证的API