ASP.NET Core框架探索之Authentication

今天我們來探索一下ASP.NET Core中關於許可權認證,所謂許可權認證,就是通過某些方式獲取到用戶的資訊。

需要開啟許可權認證,我們首先需要在容器中注入認證服務,使用services.AddAuthentication。進入該方法的源碼,最重要的其實就是AddAuthenticationCore方法,他向容器中注入了認證體系中很重要的對象:IAuthenticationServiceIAuthenticationHandlerProviderIAuthenticationSchemeProvider

 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框架的解讀,希望有收穫的小夥伴推薦支援一下,有疑問可評論區留言討論!

Tags: