Swagger如何訪問Ocelot中帶權限驗證的API

先亮源代碼:https://github.com/axzxs2001/Asp.NetCoreExperiment/tree/master/Asp.NetCoreExperiment/SwaggerDemohtml

這篇博文不是對asp.net core中使用Swagger做介紹,由於社區博客做了詳細說明。git

今天主要說一下Swagger在Ocelot網關權限驗證模式下的訪問,以及Swagger請求應答的數據格式。github

首先建立四個項目:web

SwaggerOcelot:asp.net core web api類型,api網關項目json

SwaggerAuthorize:asp.net core web api類型,用戶驗證項目api

SwaggerAPI01:asp.net core web api類型,api 1項目app

SWaggerAPI02:asp.net core web api類型,api 2項目asp.net

首先在四個項目中添加基於Jwt的Toekn認證,參見http://www.javashuo.com/article/p-dkxnyhbd-kq.htmlasync

再在四個項目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 }

運行效果:

先看登陸

 

再看api訪問

相關文章
相關標籤/搜索