今天我們來探索一下ASP.NET Core中關于權限認證,所謂權限認證,就是通過某些方式獲取到用戶的資訊,
需要開啟權限認證,我們首先需要在容器中注入認證服務,使用services.AddAuthentication,進入該方法的原始碼,最重要的其實就是AddAuthenticationCore方法,他向容器中注入了認證體系中很重要的物件:IAuthenticationService、IAuthenticationHandlerProvider、IAuthenticationSchemeProvider
1 public static IServiceCollection AddAuthenticationCore(this IServiceCollection services) 2 { 3 if (services == null) 4 { 5 throw new ArgumentNullException(nameof(services)); 6 } 7 8 services.TryAddScoped<IAuthenticationService, AuthenticationService>(); 9 services.TryAddSingleton<IClaimsTransformation, NoopClaimsTransformation>(); // Can be replaced with scoped ones that use DbContext 10 services.TryAddScoped<IAuthenticationHandlerProvider, AuthenticationHandlerProvider>(); 11 services.TryAddSingleton<IAuthenticationSchemeProvider, AuthenticationSchemeProvider>(); 12 return services; 13 }View Code
然后還需要在Configure管道處理中加上需要權限認證app.UseAuthentication(),該方法會向處理管道中添加名為AuthenticationMiddleware的中間件,具體一個請求到來時,框架是如何進行權限認證的處理邏輯都在這里,
下面我們就大致討論一下AuthenticationMiddleware中間件中對于權限認證程序的細節:
1、請求進入認證環節,首先會進入IAuthenticationSchemeProvider物件拿到AuthenticationOptions物件中的IList<AuthenticationSchemeBuilder>集合,所有注冊到認證體系中的認證方案都會在該集合中拿到,
2、通過回圈集合,呼叫AuthenticationSchemeBuilder物件的Builder方法去獲得所有的認證方案AuthenticationScheme,將得到的AuthenticationScheme以AuthenticationScheme.Name作為key保存到AuthenticationSchemeProvider物件的字典集合IDictionary<string, AuthenticationScheme>中,這樣AuthenticationSchemeProvider就擁有了回傳AuthenticationScheme的能力,通過傳入認證方案名稱,即可得到方案物件,
3、拿到了AuthenticationScheme物件,其認證處理型別即可在HandlerType屬性中得到,然后在IAuthenticationHandlerProvider的實體物件中根據HandlerType創建一個認證處理物件IAuthenticationHandler,最后呼叫該物件的AuthenticateAsync方法就是完成具體的認證處理邏輯,需要注意的是這里的IAuthenticationHandler物件會根據每個AuthenticationScheme具備的認證處理邏輯而來,所以得到的AuthenticationScheme不同,認證處理的邏輯就不同,
下圖是我針對認證流程畫的一個的大致程序:

以上就是用戶認證體系中大致認證邏輯,當然通過以上的描述還會存在以下疑點:
1、進入認證環節后,AuthenticationSchemeProvider可能會擁有很多個AuthenticationScheme,需要通過傳入某個認證方案名稱來拿到具體的AuthenticationScheme,那么這個傳入的動作是在哪里呢?
2、AuthenticationSchemeProvider物件在實體化的時候從AuthenticationOptions物件中獲取IList<AuthenticationSchemeBuilder>集合進行回圈Builder得到AuthenticationScheme,那AuthenticationOptions中該集合的資料是在什么時候添加進去的呢?
3、如何在認證體系中添加需要的AuthenticationScheme呢?
以Cookie為例,我們會在向容器添加認證服務的時候就會指定默認的認證方案名稱:service.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme),方法回傳AuthenticationBuilder,但此刻還只是組建了認證服務的框架,還需要向這個框架中添加處理認證的方案,所以會通過AuthenticationBuilder.AddCookie將Cooike的認證方案添加進來,當然我們可以添加很多個方案,比如使用JWT進行認證,但實際認證程序還是根據傳遞的默認方案的名稱進行的,
今天的分享就到這里,后續會繼續帶來更多關于ASP.NET Core框架的解讀,希望有識訓的小伙伴推薦支持一下,有疑問可評論區留言討論!
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/445245.html
標籤:.NET Core
上一篇:C#-7 結構和列舉
