1. 程式人生 > 實用技巧 >netCore微服務學習筆記(一):IdentityServer4客戶端授權

netCore微服務學習筆記(一):IdentityServer4客戶端授權

關於IdentityServer4介紹,可詳見https://www.cnblogs.com/sheng-jie/p/9430920.html;

1.搭建測試程式:

新建net Core應用:

2.新增引用程式:通過NuGet安裝IdentityServer4或者通過程式包管理執行Install-Package IdentityServer4安裝依賴包。

這裡用的是3.14版本,新的版本會出現問題,後面說下

3:編輯程式碼

新建一個Config類,管理Identity資源,程式碼如下:

 1 using IdentityServer4.Models;
 2 using System.Collections.Generic;
3 namespace IdentityClientDemo 4 { 5 public static class IdentityClientConfig 6 { 7 public static IEnumerable<IdentityResource> GetIdentityResourceResources() 8 { 9 return new List<IdentityResource> 10 { 11 new IdentityResources.OpenId(),
12 }; 13 } 14 // scopes define the API resources in your system 15 public static IEnumerable<ApiResource> GetApiResources() 16 { 17 //api資源({資源名稱}{描述}) 18 return new List<ApiResource> 19 { 20 new ApiResource("
Api", "Api"), 21 }; 22 } 23 24 /// <summary> 25 /// 新增客戶端 26 /// </summary> 27 /// <returns></returns> 28 public static IEnumerable<Client> GetClients() 29 { 30 return new List<Client> 31 { 32 new Client 33 { 34 //客戶端id,必須唯一 35 ClientId = "client", 36 AllowedGrantTypes = GrantTypes.ClientCredentials,//授權方式,這裡採用的是客戶端認證模式 37 ClientSecrets = 38 { 39 new Secret("secret".Sha256()) 40 }, 41 AllowedScopes = 42 { 43 "Api", 44 } 45 } 46 }; 47 } 48 } 49 }

然後再startup.class中注入服務:

 1 using Microsoft.AspNetCore.Builder;
 2 using Microsoft.AspNetCore.Hosting;
 3 using Microsoft.Extensions.Configuration;
 4 using Microsoft.Extensions.DependencyInjection;
 5 using Microsoft.Extensions.Hosting;
 6 namespace IdentityClientDemo
 7 {
 8     public class Startup
 9     {
10         public Startup(IConfiguration configuration)
11         {
12             Configuration = configuration;
13         }
14 
15         public IConfiguration Configuration { get; }
16 
17         // This method gets called by the runtime. Use this method to add services to the container.
18         public void ConfigureServices(IServiceCollection services)
19         {
20 
21             services.AddIdentityServer()
22                  .AddDeveloperSigningCredential()
23                 .AddInMemoryApiResources(IdentityClientConfig.GetApiResources())//Api資源資訊
24                 .AddInMemoryClients(IdentityClientConfig.GetClients());//客戶端資訊
25             services.AddControllers();
26         }
27 
28         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
29         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
30         {
31             if (env.IsDevelopment())
32             {
33                 app.UseDeveloperExceptionPage();
34             }
35 
36             app.UseHttpsRedirection();
37 
38             app.UseRouting();
39 
40             app.UseAuthorization();
41             app.UseIdentityServer();
42             app.UseEndpoints(endpoints =>
43             {
44                 endpoints.MapControllers();
45             });
46         }
47     }
48 }
View Code

修改launchSetting.json檔案,編輯

3.執行測試:

執行程式,在PostMan中輸入網站https://localhost:44350/.well-known/openid-configuration,可看到下圖:

通過該路徑"https://localhost:44350/connect/token",可以獲取到token

  

其中body中的引數分別為:

  grant_type :對應apiAllowedGrantTypes 型別表示授權模式

client_id : 對應clentID

client_secret: 客戶端祕鑰

4.建立api服務程式:

新增“IdentityServer4.AccessTokenValidation“引用,然後再startup.class中注入服務,

 1 using Microsoft.AspNetCore.Authentication.JwtBearer;
 2 using Microsoft.AspNetCore.Builder;
 3 using Microsoft.AspNetCore.Hosting;
 4 using Microsoft.Extensions.Configuration;
 5 using Microsoft.Extensions.DependencyInjection;
 6 using Microsoft.Extensions.Hosting;
 7 namespace IdentityServerDemo
 8 {
 9     public class Startup
10     {
11         public Startup(IConfiguration configuration)
12         {
13             Configuration = configuration;
14         }
15 
16         public IConfiguration Configuration { get; }
17 
18         // This method gets called by the runtime. Use this method to add services to the container.
19         public void ConfigureServices(IServiceCollection services)
20         {
21             
22             services
23              .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//JwtBearerDefaults.AuthenticationScheme為“Beaer"
24              .AddIdentityServerAuthentication("Bearer", options =>
25              {
26                  options.Authority = "http://localhost:44350";
27                  //options.Authority = "http://localhost:5003";
28                  options.RequireHttpsMetadata = false;
29                  options.ApiName = "Api"; //服務的名稱,對應Identity Server當中的Api資源名稱
30                  options.ApiSecret = "secret";
31              }); 
32             services.AddControllers();
33         }
34 
35         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
36         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
37         {
38             if (env.IsDevelopment())
39             {
40                 app.UseDeveloperExceptionPage();
41             }
42 
43             app.UseHttpsRedirection();
44 
45             app.UseRouting();
46             //新增authentication中介軟體到http管道
47             app.UseAuthentication();
48             app.UseAuthorization();
49 
50             app.UseEndpoints(endpoints =>
51             {
52                 endpoints.MapControllers();
53             });
54         }
55     }
56 }
View Code

5.測試:

api服務控制器新增authorize認證:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using Microsoft.AspNetCore.Authorization;
 5 using Microsoft.AspNetCore.Mvc;
 6 using Microsoft.Extensions.Logging;
 7 
 8 namespace IdentityServerDemo.Controllers
 9 {
10     [ApiController]
11     [Route("[controller]")]
12     [Authorize]
13     public class WeatherForecastController : ControllerBase
14     {
15         private static readonly string[] Summaries = new[]
16         {
17             "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
18         };
19 
20         private readonly ILogger<WeatherForecastController> _logger;
21 
22         public WeatherForecastController(ILogger<WeatherForecastController> logger)
23         {
24             _logger = logger;
25         }
26 
27         [HttpGet]
28         public IEnumerable<WeatherForecast> Get()
29         {
30             var rng = new Random();
31             return Enumerable.Range(1, 5).Select(index => new WeatherForecast
32             {
33                 Date = DateTime.Now.AddDays(index),
34                 TemperatureC = rng.Next(-20, 55),
35                 Summary = Summaries[rng.Next(Summaries.Length)]
36             })
37             .ToArray();
38         }
39     }
40 }
View Code

執行api服務程式,訪問“WeatherForecastController”

可以看到,目前是未授權狀態。訪問認證網站http://localhost:44350/connect/token,獲取access_token然後用配置的client向IdentityServer申請token來訪問Api資源:http://localhost:44344/weatherforecast,結果如下圖:

可以看到,已經可以正常訪問