日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

ASP.NET?Core框架探索之Authentication的權限認證過程解析_實用技巧

作者:EdisonXie ? 更新時間: 2022-05-19 編程語言

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

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

public static IServiceCollection AddAuthenticationCore(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.TryAddScoped();
            services.TryAddSingleton(); // Can be replaced with scoped ones that use DbContext
            services.TryAddScoped();
            services.TryAddSingleton();
            return services;
        }

然后還需要在Configure管道處理中加上需要權限認證app.UseAuthentication(),該方法會向處理管道中添加名為AuthenticationMiddleware的中間件,具體一個請求到來時,框架是如何進行權限認證的處理邏輯都在這里。

下面我們就大致討論一下AuthenticationMiddleware中間件中對于權限認證過程的細節:

1、請求進入認證環節,首先會進入IAuthenticationSchemeProvider對象拿到AuthenticationOptions對象中的IList集合,所有注冊到認證體系中的認證方案都會在該集合中拿到。

2、通過循環集合,調用AuthenticationSchemeBuilder對象的Builder方法去獲得所有的認證方案AuthenticationScheme,將得到的AuthenticationScheme以AuthenticationScheme.Name作為key保存到AuthenticationSchemeProvider對象的字典集合IDictionary中,這樣AuthenticationSchemeProvider就擁有了返回AuthenticationScheme的能力,通過傳入認證方案名稱,即可得到方案對象。

3、拿到了AuthenticationScheme對象,其認證處理類型即可在HandlerType屬性中得到,然后在IAuthenticationHandlerProvider的實例對象中根據HandlerType創建一個認證處理對象IAuthenticationHandler,最后調用該對象的AuthenticateAsync方法就是完成具體的認證處理邏輯。需要注意的是這里的IAuthenticationHandler對象會根據每個AuthenticationScheme具備的認證處理邏輯而來,所以得到的AuthenticationScheme不同,認證處理的邏輯就不同。

下圖是我針對認證流程畫的一個的大致過程:

?以上就是用戶認證體系中大致認證邏輯,當然通過以上的描述還會存在以下疑點:

1、進入認證環節后,AuthenticationSchemeProvider可能會擁有很多個AuthenticationScheme,需要通過傳入某個認證方案名稱來拿到具體的AuthenticationScheme,那么這個傳入的動作是在哪里呢?

2、AuthenticationSchemeProvider對象在實例化的時候從AuthenticationOptions對象中獲取IList集合進行循環Builder得到AuthenticationScheme,那AuthenticationOptions中該集合的數據是在什么時候添加進去的呢?

3、如何在認證體系中添加需要的AuthenticationScheme呢?

以Cookie為例,我們會在向容器添加認證服務的時候就會指定默認的認證方案名稱:service.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme),方法返回AuthenticationBuilder,但此刻還只是組建了認證服務的框架,還需要向這個框架中添加處理認證的方案,所以會通過AuthenticationBuilder.AddCookie將Cooike的認證方案添加進來,當然我們可以添加很多個方案,比如使用JWT進行認證,但實際認證過程還是根據傳遞的默認方案的名稱進行的。

原文鏈接:https://www.cnblogs.com/XFlyMan/p/16008208.html

欄目分類
最近更新