深度解讀.NET5 授權中介軟體執行策略

_小碼甲發表於2021-02-04

前文提要

2021.1月份我寫了一個《這難道不是.NET5 的bug? 線上求錘?》,
講述了我在實現[全域性授權訪問+特例匿名訪問] 遇到的技術困惑: [特例匿名訪問,還是走了認證流程]。

部落格園上某大佬的看法:

大概的意思是說 : 不管是匿名訪問還是鑑權訪問,均先識別使用者身份,再決定跳過授權/應用授權! [有身份訪問 MVC Login]這個場景可以佐證這個看法。

頭腦風暴

後來我又仔細檢視看了授權的原始碼,發現並不完整, 請看官仔細觀察我原文的示例,
端點路由還有一個[健康檢查],端點加上了[AllowAnonymous]

endpoints.MapHealthChecks("/healthz").AllowAnonymous().WithDisplayName("healthz");

這個端點並沒有進入認證流程,從授權中介軟體原始碼上看也是如此。

故官方原始碼是否能進入認證邏輯: 關鍵是看能不能在端點上包含授權策略

var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();   
  var policy = await AuthorizationPolicy.CombineAsync(_policyProvider, authorizeData);
  if (policy == null)
 {
     await _next(context);
     return;
  }

健康檢查端點直接應用了[AllowAnonymous](實際上你可以不加), 這樣就沒有授權策略(policy= null),這個時候自然跳過後續,進入業務邏輯。

甚至, 你可以這樣寫:
endpoints.MapControllers().RequireAuthorization().AllowAnonymous().WithDisplayName("default");
這樣的程式碼也要進入認證邏輯,因為它包含了授權宣告。

根據以上分析,.NET 5授權中介軟體的流程是這樣的:

The official said:

Authorization is orthogonal and independent from authentication. However, authorization requires an authentication mechanism. Authentication is the process of ascertaining who a user is. Authentication may create one or more identities for the current user.
授權是正交的並且獨立於驗證。但是,授權需要身份驗證機制。身份驗證是確定使用者身份的過程。認證可以為當前使用者建立一個或多個身份。

思緒整理

我試圖以一種流暢的、能自然其說的思路來理解官方的設計理念。

我們捋一捋:

當我“樸素的需求”到達端點時,端點第一時間拿到平鋪的所有後設資料資訊metadata

**針對這種矛盾體資訊, 確實有不同的設計策略: **

**我理解的匿名優先: 不需要認證; **

官方認定的匿名優先,是在身份登記的前提下,匿名訪問優先。。​


也許我將”匿名優先“與“認證”聯絡在一起,並不合適,
官方可是將AllowAnonymous 放在授權元件的範疇。

Authorization components, including the AuthorizeAttribute and AllowAnonymousAttribute attributes, are found in the Microsoft.AspNetCore.Authorization namespace.

就這樣吧, 匿名訪問不表示"無需認證"​; 匿名訪問 是 授權模組的內容​;授權的前提是認證。 ​

相關文章