.NET Core微服務之基於Ocelot+IdentityServer實現統一驗證與授權
一、案例結構總覽
這裡,假設我們有兩個客戶端(一個Web網站,一個移動App),他們要使用系統,需要先向IdentityService進行Login以進行驗證並獲取Token,在IdentityService的驗證過程中會訪問資料庫以驗證。然後再帶上Token通過API閘道器去訪問具體的API Service。這裡我們的IdentityService基於IdentityServer4開發,它具有統一登入驗證和授權的功能。當然,我們也可以將統一登入驗證獨立出來,寫成一個單獨的API Service,託管在API閘道器中,這裡我不想太麻煩,便直接將其也寫在了IdentityService中。
二、改寫API Gateway
這裡主要基於前兩篇已經搭好的API Gateway進行改寫,如不熟悉,可以先瀏覽前兩篇文章:Part 1和Part 2。
2.1 配置檔案的改動
...... "AuthenticationOptions": { "AuthenticationProviderKey": "ClientServiceKey", "AllowedScopes": [] } ...... "AuthenticationOptions": { "AuthenticationProviderKey": "ProductServiceKey", "AllowedScopes": [] } ......
上面分別為兩個示例API Service增加Authentication的選項,為其設定ProviderKey。下面會對不同的路由規則設定的ProviderKey設定具體的驗證方式。
2.2 改寫StartUp類
public void ConfigureServices(IServiceCollection services) { // IdentityServer #region IdentityServerAuthenticationOptions => need to refactor Action<IdentityServerAuthenticationOptions> isaOptClient = option => { option.Authority = Configuration["IdentityService:Uri"]; option.ApiName = "clientservice"; option.RequireHttpsMetadata = Convert.ToBoolean(Configuration["IdentityService:UseHttps"]); option.SupportedTokens = SupportedTokens.Both; option.ApiSecret = Configuration["IdentityService:ApiSecrets:clientservice"]; }; Action<IdentityServerAuthenticationOptions> isaOptProduct = option => { option.Authority = Configuration["IdentityService:Uri"]; option.ApiName = "productservice"; option.RequireHttpsMetadata = Convert.ToBoolean(Configuration["IdentityService:UseHttps"]); option.SupportedTokens = SupportedTokens.Both; option.ApiSecret = Configuration["IdentityService:ApiSecrets:productservice"]; }; #endregion services.AddAuthentication() .AddIdentityServerAuthentication("ClientServiceKey", isaOptClient) .AddIdentityServerAuthentication("ProductServiceKey", isaOptProduct); // Ocelot services.AddOcelot(Configuration); ...... }
這裡的ApiName主要對應於IdentityService中的ApiResource中定義的ApiName。這裡用到的配置檔案定義如下:
View Code
這裡的定義方式,我暫時還沒想好怎麼重構,不過肯定是需要重構的,不然這樣一個一個寫比較繁瑣,且不利於配置。
三、新增IdentityService
這裡我們會基於之前基於IdentityServer的兩篇文章,新增一個IdentityService,不熟悉的朋友可以先瀏覽一下Part 1和Part 2。
3.1 準備工作
新建一個ASP.NET Core Web API專案,繫結埠5100,NuGet安裝IdentityServer4。配置好證書,並設定其為“較新則複製”,以便能夠在生成目錄中讀取到。
3.2 定義一個InMemoryConfiguration用於測試
/// <summary> /// One In-Memory Configuration for IdentityServer => Just for Demo Use /// </summary> public class InMemoryConfiguration { public static IConfiguration Configuration { get; set; } /// <summary> /// Define which APIs will use this IdentityServer /// </summary> /// <returns></returns> public static IEnumerable<ApiResource> GetApiResources() { return new[] { new ApiResource("clientservice", "CAS Client Service"), new ApiResource("productservice", "CAS Product Service"), new ApiResource("agentservice", "CAS Agent Service") }; } /// <summary> /// Define which Apps will use thie IdentityServer /// </summary> /// <returns></returns> public static IEnumerable<Client> GetClients() { return new[] { new Client { ClientId = "cas.sg.web.nb", ClientName = "CAS NB System MPA Client", ClientSecrets = new [] { new Secret("websecret".Sha256()) }, AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, AllowedScopes = new [] { "clientservice", "productservice", IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile } }, new Client { ClientId = "cas.sg.mobile.nb", ClientName = "CAS NB System Mobile App Client", ClientSecrets = new [] { new Secret("mobilesecret".Sha256()) }, AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, AllowedScopes = new [] { "productservice", IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile } }, new Client { ClientId = "cas.sg.spa.nb", ClientName = "CAS NB System SPA Client", ClientSecrets = new [] { new Secret("spasecret".Sha256()) }, AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, AllowedScopes = new [] { "agentservice", "clientservice", "productservice", IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile } }, new Client { ClientId = "cas.sg.mvc.nb.implicit", ClientName = "CAS NB System MVC App Client", AllowedGrantTypes = GrantTypes.Implicit, RedirectUris = { Configuration["Clients:MvcClient:RedirectUri"] }, PostLogoutRedirectUris = { Configuration["Clients:MvcClient:PostLogoutRedirectUri"] }, AllowedScopes = new [] { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, "agentservice", "clientservice", "productservice" }, //AccessTokenLifetime = 3600, // one hour AllowAccessTokensViaBrowser = true // can return access_token to this client } }; } /// <summary> /// Define which IdentityResources will use this IdentityServer /// </summary> /// <returns></returns> public static IEnumerable<IdentityResource> GetIdentityResources() { return new List<IdentityResource> { new IdentityResources.OpenId(), new IdentityResources.Profile(), }; } }
這裡使用了上一篇的內容,不再解釋。實際環境中,則應該考慮從NoSQL或資料庫中讀取。
3.3 定義一個ResourceOwnerPasswordValidator
在IdentityServer中,要實現自定義的驗證使用者名稱和密碼,需要實現一個介面:IResourceOwnerPasswordValidator
public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator { private ILoginUserService loginUserService; public ResourceOwnerPasswordValidator(ILoginUserService _loginUserService) { this.loginUserService = _loginUserService; } public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { LoginUser loginUser = null; bool isAuthenticated = loginUserService.Authenticate(context.UserName, context.Password, out loginUser); if (!isAuthenticated) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Invalid client credential"); } else { context.Result = new GrantValidationResult( subject : context.UserName, authenticationMethod : "custom", claims : new Claim[] { new Claim("Name", context.UserName), new Claim("Id", loginUser.Id.ToString()), new Claim("RealName", loginUser.RealName), new Claim("Email", loginUser.Email) } ); } return Task.CompletedTask; } }
這裡的ValidateAsync方法中(你也可以把它寫成非同步的方式,這裡使用的是同步的方式),會呼叫EF去訪問資料庫進行驗證,資料庫的定義如下(密碼應該做加密,這裡只做demo,沒用弄):
至於EF部分,則是一個典型的簡單的Service呼叫Repository的邏輯,下面只貼Repository部分:
View Code
其他具體邏輯請參考示例程式碼。
3.4 改寫StarUp類
public void ConfigureServices(IServiceCollection services) { // IoC - DbContext services.AddDbContextPool<IdentityDbContext>( options => options.UseSqlServer(Configuration["DB:Dev"])); // IoC - Service & Repository services.AddScoped<ILoginUserService, LoginUserService>(); services.AddScoped<ILoginUserRepository, LoginUserRepository>(); // IdentityServer4 string basePath = PlatformServices.Default.Application.ApplicationBasePath; InMemoryConfiguration.Configuration = this.Configuration; services.AddIdentityServer() .AddSigningCredential(new X509Certificate2(Path.Combine(basePath, Configuration["Certificates:CerPath"]), Configuration["Certificates:Password"])) //.AddTestUsers(InMemoryConfiguration.GetTestUsers().ToList()) .AddInMemoryIdentityResources(InMemoryConfiguration.GetIdentityResources()) .AddInMemoryApiResources(InMemoryConfiguration.GetApiResources()) .AddInMemoryClients(InMemoryConfiguration.GetClients()) .AddResourceOwnerValidator<ResourceOwnerPasswordValidator>() .AddProfileService<ProfileService>(); ...... }
這裡高亮的是新增的部分,為了實現自定義驗證。關於ProfileService的定義如下:
View Code
3.5 新增統一Login入口
這裡新增一個LoginController:
[Produces("application/json")] [Route("api/Login")] public class LoginController : Controller { private IConfiguration configuration; public LoginController(IConfiguration _configuration) { configuration = _configuration; } [HttpPost] public async Task<ActionResult> RequestToken([FromBody]LoginRequestParam model) { Dictionary<string, string> dict = new Dictionary<string, string>(); dict["client_id"] = model.ClientId; dict["client_secret"] = configuration[$"IdentityClients:{model.ClientId}:ClientSecret"]; dict["grant_type"] = configuration[$"IdentityClients:{model.ClientId}:GrantType"]; dict["username"] = model.UserName; dict["password"] = model.Password; using (HttpClient http = new HttpClient()) using (var content = new FormUrlEncodedContent(dict)) { var msg = await http.PostAsync(configuration["IdentityService:TokenUri"], content); if (!msg.IsSuccessStatusCode) { return StatusCode(Convert.ToInt32(msg.StatusCode)); } string result = await msg.Content.ReadAsStringAsync(); return Content(result, "application/json"); } } }
這裡假設客戶端會傳遞使用者名稱,密碼以及客戶端ID(ClientId,比如上面InMemoryConfiguration中的cas.sg.web.nb或cas.sg.mobile.nb)。然後構造引數再呼叫connect/token介面進行身份驗證和獲取token。這裡將client_secret等機密資訊封裝到了伺服器端,無須客戶端傳遞(對於機密資訊一般也不會讓客戶端知道):
"IdentityClients": { "cas.sg.web.nb": { "ClientSecret": "websecret", "GrantType": "password" }, "cas.sg.mobile.nb": { "ClientSecret": "mobilesecret", "GrantType": "password" } }
四、改寫業務API Service
4.1 ClientService
(1)安裝IdentityServer4.AccessTokenValidation
NuGet>Install-Package IdentityServer4.AccessTokenValidation
(2)改寫StartUp類
public IServiceProvider ConfigureServices(IServiceCollection services) { ...... // IdentityServer services.AddAuthentication(Configuration["IdentityService:DefaultScheme"]) .AddIdentityServerAuthentication(options => { options.Authority = Configuration["IdentityService:Uri"]; options.RequireHttpsMetadata = Convert.ToBoolean(Configuration["IdentityService:UseHttps"]); }); ...... }
這裡配置檔案的定義如下:
"IdentityService": { "Uri": "http://localhost:5100", "DefaultScheme": "Bearer", "UseHttps": false, "ApiSecret": "clientsecret" }
4.2 ProductService
與ClientService一致,請參考示例程式碼。
五、測試
5.1 測試Client: cas.sg.web.nb
(1)統一驗證&獲取token
(2)訪問clientservice (by API閘道器)
(3)訪問productservice(by API閘道器)
5.2 測試Client: cas.sg.mobile.nb
由於在IdentityService中我們定義了一個mobile的客戶端,但是其訪問許可權只有productservice,所以我們來測試一下:
(1)統一驗證&獲取token
(2)訪問ProductService(by API閘道器)
(3)訪問ClientService(by API閘道器) => 401 Unauthorized
六、小結
本篇主要基於前面Ocelot和IdentityServer的文章的基礎之上,將Ocelot和IdentityServer進行結合,通過建立IdentityService進行統一的身份驗證和授權,最後演示了一個案例以說明如何實現。不過,本篇實現的Demo還存在諸多不足,比如需要重構的程式碼較多如閘道器中各個Api的驗證選項的註冊,沒有對各個請求做使用者角色和許可權的驗證等等,相信隨著研究和深入的深入,這些都可以逐步解決。後續會探索一下資料一致性的基本知識以及框架使用,到時再做一些分享。
示例程式碼
Click Here => 點我進入GitHub
參考資料
楊中科,《.NET Core微服務介紹課程》