一、前言
回顧:基於.NetCore3.1系列 —— 認證授權方案之授權揭祕 (上篇)
在上一篇中,主要講解了授權在配置方面的原始碼,從新增授權配置開始,我們引入了需要的授權配置選項,而不同的授權要求構建不同的策略方式,從而實現一種自己滿意的授權需求配置要求。
在這一節中,繼續上一篇的內容往下深入瞭解授權內部機制的奧祕以及是如何實現執行授權流程的。
二、說明
在上一篇中,我們通過定義授權策略,檢視原始碼發現,在對授權配置AuthorizationOptions
之後,授權系統通過DI的方式註冊了幾個核心的預設實現。
之前我們進行對步驟一的授權有了大概瞭解,所以下面我們將對步驟二進行的註冊物件進行說明。
三、開始
3.1 IAuthorizationService
授權服務介面,用來確定授權是否成功的主要服務,介面的定義為
public interface IAuthorizationService
{
Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable<IAuthorizationRequirement> requirements);
Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName);
}
兩個介面的引數不同之處在於IAuthorizationRequirement
和policyName
,分別是指定資源的一組特定要求和指定的授權名稱。
同時asp.net core還為IAuthorizationService
介面擴充了幾個方法:
public static class AuthorizationServiceExtensions
{
public static Task<AuthorizationResult> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, object resource, IAuthorizationRequirement requirement)
{
if (service == null)
{
throw new ArgumentNullException(nameof(service));
}
if (requirement == null)
{
throw new ArgumentNullException(nameof(requirement));
}
return service.AuthorizeAsync(user, resource, new IAuthorizationRequirement[] { requirement });
}
public static Task<AuthorizationResult> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, object resource, AuthorizationPolicy policy)
{
if (service == null)
{
throw new ArgumentNullException(nameof(service));
}
if (policy == null)
{
throw new ArgumentNullException(nameof(policy));
}
return service.AuthorizeAsync(user, resource, policy.Requirements);
}
public static Task<AuthorizationResult> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, AuthorizationPolicy policy)
{
if (service == null)
{
throw new ArgumentNullException(nameof(service));
}
if (policy == null)
{
throw new ArgumentNullException(nameof(policy));
}
return service.AuthorizeAsync(user, resource: null, policy: policy);
}
public static Task<AuthorizationResult> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, string policyName)
{
if (service == null)
{
throw new ArgumentNullException(nameof(service));
}
if (policyName == null)
{
throw new ArgumentNullException(nameof(policyName));
}
return service.AuthorizeAsync(user, resource: null, policyName: policyName);
}
}
介面的預設實現為DefaultAuthorizationService
DefaultAuthorizationService
的實現主要是用來對 IAuthorizationRequirement物件的授權檢驗。
public class DefaultAuthorizationService : IAuthorizationService
{
private readonly AuthorizationOptions _options;
private readonly IAuthorizationHandlerContextFactory _contextFactory;
private readonly IAuthorizationHandlerProvider _handlers;
private readonly IAuthorizationEvaluator _evaluator;
private readonly IAuthorizationPolicyProvider _policyProvider;
private readonly ILogger _logger;
public DefaultAuthorizationService(IAuthorizationPolicyProvider policyProvider, IAuthorizationHandlerProvider handlers, ILogger<DefaultAuthorizationService> logger, IAuthorizationHandlerContextFactory contextFactory, IAuthorizationEvaluator evaluator, IOptions<AuthorizationOptions> options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (policyProvider == null)
{
throw new ArgumentNullException(nameof(policyProvider));
}
if (handlers == null)
{
throw new ArgumentNullException(nameof(handlers));
}
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
if (contextFactory == null)
{
throw new ArgumentNullException(nameof(contextFactory));
}
if (evaluator == null)
{
throw new ArgumentNullException(nameof(evaluator));
}
_options = options.Value;
_handlers = handlers;
_policyProvider = policyProvider;
_logger = logger;
_evaluator = evaluator;
_contextFactory = contextFactory;
}
public async Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable<IAuthorizationRequirement> requirements)
{
if (requirements == null)
{
throw new ArgumentNullException(nameof(requirements));
}
var authContext = _contextFactory.CreateContext(requirements, user, resource);
var handlers = await _handlers.GetHandlersAsync(authContext);
foreach (var handler in handlers)
{
await handler.HandleAsync(authContext);
if (!_options.InvokeHandlersAfterFailure && authContext.HasFailed)
{
break;
}
}
var result = _evaluator.Evaluate(authContext);
if (result.Succeeded)
{
_logger.UserAuthorizationSucceeded();
}
else
{
_logger.UserAuthorizationFailed();
}
return result;
}
public async Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName)
{
if (policyName == null)
{
throw new ArgumentNullException(nameof(policyName));
}
var policy = await _policyProvider.GetPolicyAsync(policyName);
if (policy == null)
{
throw new InvalidOperationException($"No policy found: {policyName}.");
}
return await this.AuthorizeAsync(user, resource, policy);
}
}
通過上面的程式碼可以發現,在物件例項中,通過建構函式的方式分別注入了IAuthorizationPolicyProvider
、IAuthorizationHandlerProvider
、IAuthorizationEvaluator
、IAuthorizationHandlerContextFactory
這幾個核心服務,以及配置選項的AuthorizationOptions物件,再通過實現的方法AuthorizeAsync
可以看出,在方法中呼叫GetPolicyAsync
來獲取Requirements
,具體的可以看一下上一節的AuthorizationPolicy,而後在根據授權上下文來判斷。
這裡就用到了注入的幾個核心物件來實現完成授權的。下面會分別介紹到的。
3.2 IAuthorizationPolicyProvider
由上面的IAuthorizationServer
介面的預設實現可以發現,在進行授權檢驗的時候,DefaultAuthorizationService
會利用注入的IAuthorizationPolicyProvider
服務來提供註冊的授權策略,所以我們檢視原始碼發現,介面提供 了預設的授權策略GetDefaultPolicyAsync
和指定名稱的授權策略·GetPolicyAsync(string policyName)
的方法。
public interface IAuthorizationPolicyProvider
{
Task<AuthorizationPolicy> GetPolicyAsync(string policyName);
Task<AuthorizationPolicy> GetDefaultPolicyAsync();
Task<AuthorizationPolicy> GetFallbackPolicyAsync();
}
再加上在使用[Authorize]
進行策略授權的時候,會根據提供的介面方法來獲取指定的授權策略。
IAuthorizationPolicyProvider
來根據名稱獲取到策略物件,預設實現為DefaultAuthorizationPolicyProvider
:
DefaultAuthorizationPolicyProvider
public class DefaultAuthorizationPolicyProvider : IAuthorizationPolicyProvider
{
private readonly AuthorizationOptions _options;
private Task<AuthorizationPolicy> _cachedDefaultPolicy;
private Task<AuthorizationPolicy> _cachedFallbackPolicy;
public DefaultAuthorizationPolicyProvider(IOptions<AuthorizationOptions> options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_options = options.Value;
}
public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
{
return GetCachedPolicy(ref _cachedDefaultPolicy, _options.DefaultPolicy);
}
public Task<AuthorizationPolicy> GetFallbackPolicyAsync()
{
return GetCachedPolicy(ref _cachedFallbackPolicy, _options.FallbackPolicy);
}
private Task<AuthorizationPolicy> GetCachedPolicy(ref Task<AuthorizationPolicy> cachedPolicy, AuthorizationPolicy currentPolicy)
{
var local = cachedPolicy;
if (local == null || local.Result != currentPolicy)
{
cachedPolicy = local = Task.FromResult(currentPolicy);
}
return local;
}
public virtual Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
{
return Task.FromResult(_options.GetPolicy(policyName));
}
}
由上面的程式碼可以看出,在實現DefaultAuthorizationPolicyProvider
物件進行建構函式的方式注入了IOptions<AuthorizationOptions> options
服務來提供配置選項AuthorizationOptions
(不懂的可以檢視上一篇的AuthorizationOptions),再通過實現的方法可以看出是如何獲取到註冊的授權策略的了。附加一個圖片
在上一章中介紹過,我們定義的策略都儲存在AuthorizationOptions的中PolicyMap
字典中,由上程式碼可以發現這字典的用處。
3.3 IAuthorizationHandlerContextFactory
先看看這個介面的原始碼
public interface IAuthorizationHandlerContextFactory
{
AuthorizationHandlerContext CreateContext(IEnumerable<IAuthorizationRequirement> requirements, ClaimsPrincipal user, object resource);
}
介面定義了一個唯一的方法CreateContext
,作用在於建立授權上下文AuthorizationHandlerContext
物件。介面預設實現方式
public class DefaultAuthorizationHandlerContextFactory : IAuthorizationHandlerContextFactory
{
public virtual AuthorizationHandlerContext CreateContext(IEnumerable<IAuthorizationRequirement> requirements, ClaimsPrincipal user, object resource)
{
return new AuthorizationHandlerContext(requirements, user, resource);
}
}
再來看看AuthorizationHandlerContext
授權上下文物件,可以看出,上下文中主要包括使用者的Claims和授權策略的要求Requirements
public class AuthorizationHandlerContext
{
private HashSet<IAuthorizationRequirement> _pendingRequirements;
private bool _failCalled;
private bool _succeedCalled;
public AuthorizationHandlerContext(
IEnumerable<IAuthorizationRequirement> requirements,
ClaimsPrincipal user,
object resource)
{
if (requirements == null)
{
throw new ArgumentNullException(nameof(requirements));
}
Requirements = requirements;
User = user;
Resource = resource;
_pendingRequirements = new HashSet<IAuthorizationRequirement>(requirements);
}
public virtual IEnumerable<IAuthorizationRequirement> Requirements { get; }
public virtual ClaimsPrincipal User { get; }
public virtual object Resource { get; }
public virtual IEnumerable<IAuthorizationRequirement> PendingRequirements { get { return _pendingRequirements; } }
public virtual bool HasFailed { get { return _failCalled; } }
public virtual bool HasSucceeded
{
get
{
return !_failCalled && _succeedCalled && !PendingRequirements.Any();
}
}
public virtual void Fail()
{
_failCalled = true;
}
public virtual void Succeed(IAuthorizationRequirement requirement)
{
_succeedCalled = true;
_pendingRequirements.Remove(requirement);
}
}
因此,在下面我們剛好會提到了IAuthorizationHandlerProvider
中的方法,可以根據授權上下文獲取到請求呼叫的處理程式。
3.4 IAuthorizationHandlerProvider
這個是介面的方法,作用是獲取所有的授權Handler
public interface IAuthorizationHandlerProvider
{
Task<IEnumerable<IAuthorizationHandler>> GetHandlersAsync(AuthorizationHandlerContext context);
}
根據之前提到的授權上下文作為GetHandlersAsync
方法引數物件來提取IAuthorizationHandler
物件。
預設介面的實現為DefaultAuthorizationHandlerProvider
, 處理程式的預設實現,為授權請求提供IAuthorizationHandler
public class DefaultAuthorizationHandlerProvider : IAuthorizationHandlerProvider
{
private readonly IEnumerable<IAuthorizationHandler> _handlers;
public DefaultAuthorizationHandlerProvider(IEnumerable<IAuthorizationHandler> handlers)
{
if (handlers == null)
{
throw new ArgumentNullException(nameof(handlers));
}
_handlers = handlers;
}
public Task<IEnumerable<IAuthorizationHandler>> GetHandlersAsync(AuthorizationHandlerContext context)
=> Task.FromResult(_handlers);
}
從預設實現的方式可以看出,利用建構函式的方式注入預設的IAuthorizationHandler
的物件,但是我們再看看介面的實現方法可以發現,GetHandlersAsync
返回的IAuthorizationHandler
物件並不是從給定的AuthorizationHandlerContext
上下文中獲取的,而是直接通過建構函式的方式注入得到的。
這個時候,你可能會問,那麼IAuthorizationHandler
是在哪裡注入的呢?
對應下面的 IAuthorizationHandler
3.5 IAuthorizationEvaluator
由DefaultAuthorizationService
中的授權方法過程呼叫了
var result = _evaluator.Evaluate(authContext);
IAuthorizationEvaluator
介面,來確定授權結果是否成功。
public interface IAuthorizationEvaluator
{
AuthorizationResult Evaluate(AuthorizationHandlerContext context);
}
IAuthorizationEvaluator
的唯一方法Evaluate
,該方法會根據之前提供的授權上下文返回一個表示授權成功的AuthorizationResult
物件。預設實現為DefaultAuthorizationEvaluator
public class DefaultAuthorizationEvaluator : IAuthorizationEvaluator
{
public AuthorizationResult Evaluate(AuthorizationHandlerContext context)
=> context.HasSucceeded
? AuthorizationResult.Success()
: AuthorizationResult.Failed(context.HasFailed
? AuthorizationFailure.ExplicitFail()
: AuthorizationFailure.Failed(context.PendingRequirements));
}
由預設實現可以看出,AuthorizationHandlerContext
物件的HasSucceeded
屬性決定了授權是否成功。當驗證通過時,授權上下文中的HasSucceeded
才會為True。
其中的AuthorizationResult
和AuthorizationFailure
分別為
public class AuthorizationResult
{
private AuthorizationResult() { }
public bool Succeeded { get; private set; }
public AuthorizationFailure Failure { get; private set; }
public static AuthorizationResult Success() => new AuthorizationResult { Succeeded = true };
public static AuthorizationResult Failed(AuthorizationFailure failure) => new AuthorizationResult { Failure = failure };
public static AuthorizationResult Failed() => new AuthorizationResult { Failure = AuthorizationFailure.ExplicitFail() };
}
public class AuthorizationFailure
{
private AuthorizationFailure() { }
public bool FailCalled { get; private set; }
public IEnumerable<IAuthorizationRequirement> FailedRequirements { get;private set; }
public static AuthorizationFailure ExplicitFail()
=> new AuthorizationFailure
{
FailCalled = true,
FailedRequirements = new IAuthorizationRequirement[0]
};
public static AuthorizationFailure Failed(IEnumerable<IAuthorizationRequirement> failed)
=> new AuthorizationFailure { FailedRequirements = failed };
}
這裡的兩個授權結果 正是IAuthorizationService
進行實現授權AuthorizeAsync
來完成校驗返回的結果。
3.6 IAuthorizationHandler
介面方式實現,判斷是否授權,實現此介面的類
public interface IAuthorizationHandler
{
Task HandleAsync(AuthorizationHandlerContext context);
}
如果允許授權,可通過此介面的方法來決定是否允許授權。
之前我們還介紹到,我們定義的Requirement,可以直接實現
IAuthorizationHandler
介面,也可以單獨定義Handler,但是需要註冊到DI系統中去。在預設的AuthorizationHandlerProvider中,會從DI系統中獲取到我們註冊的所有Handler,最終呼叫其
HandleAsync
方法。我們在實現
IAuthorizationHandler
介面時,通常是繼承自AuthorizationHandler
來實現,它有如下定義:public abstract class AuthorizationHandler<TRequirement> : IAuthorizationHandler where TRequirement : IAuthorizationRequirement { public virtual async Task HandleAsync(AuthorizationHandlerContext context) { foreach (var req in context.Requirements.OfType<TRequirement>()) { await HandleRequirementAsync(context, req); } } protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement); }
如上,首先會在
HandleAsync
過濾出與Requirement對匹配的Handler,然後再呼叫其HandleRequirementAsync
方法。那我們定義的直接實現
IAuthorizationHandler
了介面的Requirement又是如何執行的呢?
我們可以發現,IAuthorizationHandler
在AddAuthorization
擴充方法中可以看到預設註冊了一個PassThroughAuthorizationHandler
預設實現為:
public class PassThroughAuthorizationHandler : IAuthorizationHandler
{
public async Task HandleAsync(AuthorizationHandlerContext context)
{
foreach (var handler in context.Requirements.OfType<IAuthorizationHandler>())
{
await handler.HandleAsync(context);
}
}
}
它負責呼叫該策略中所有實現了IAuthorizationHandler
介面的Requirement
。通過介面實現的方法可以看出,當PassThroughAuthorizationHandler
物件的HandleAsync
方法被執行的時候,它會從AuthroizationHanderContext
的Requirements
屬性中提取所有的IAuthoizationHandler
物件,並逐個呼叫它們的HandleAsync
方法來實施授權檢驗。
所以可以看到的出,PassThroughAuthorizationHandler
是一個特殊並且重要的授權處理器型別,其特殊之處在於它並沒有實現針對某個具體規則的授權檢驗,但是AuthorizationHandlerContext上下文所有的IAuthorizationHandler
都是通過該物件驅動執行的。
3.7 IPolicyEvaluator
介面的方式實現,為特定需求型別呼叫的授權處理程式的基類
public interface IPolicyEvaluator
{
Task<AuthenticateResult> AuthenticateAsync(AuthorizationPolicy policy, HttpContext context);
Task<PolicyAuthorizationResult> AuthorizeAsync(AuthorizationPolicy policy, AuthenticateResult authenticationResult, HttpContext context, object resource);
}
定義了兩個方法AuthenticateAsync
和AuthorizeAsync
方法
IPolicyEvaluator
的預設實現為PolicyEvaluator
public class PolicyEvaluator : IPolicyEvaluator
{
private readonly IAuthorizationService _authorization;
public PolicyEvaluator(IAuthorizationService authorization)
{
_authorization = authorization;
}
public virtual async Task<AuthenticateResult> AuthenticateAsync(AuthorizationPolicy policy, HttpContext context)
{
if (policy.AuthenticationSchemes != null && policy.AuthenticationSchemes.Count > 0)
{
ClaimsPrincipal newPrincipal = null;
foreach (var scheme in policy.AuthenticationSchemes)
{
var result = await context.AuthenticateAsync(scheme);
if (result != null && result.Succeeded)
{
newPrincipal = SecurityHelper.MergeUserPrincipal(newPrincipal, result.Principal);
}
}
if (newPrincipal != null)
{
context.User = newPrincipal;
return AuthenticateResult.Success(new AuthenticationTicket(newPrincipal, string.Join(";", policy.AuthenticationSchemes)));
}
else
{
context.User = new ClaimsPrincipal(new ClaimsIdentity());
return AuthenticateResult.NoResult();
}
}
return (context.User?.Identity?.IsAuthenticated ?? false)
? AuthenticateResult.Success(new AuthenticationTicket(context.User, "context.User"))
: AuthenticateResult.NoResult();
}
public virtual async Task<PolicyAuthorizationResult> AuthorizeAsync(AuthorizationPolicy policy, AuthenticateResult authenticationResult, HttpContext context, object resource)
{
if (policy == null)
{
throw new ArgumentNullException(nameof(policy));
}
var result = await _authorization.AuthorizeAsync(context.User, resource, policy);
if (result.Succeeded)
{
return PolicyAuthorizationResult.Success();
}
// If authentication was successful, return forbidden, otherwise challenge
return (authenticationResult.Succeeded)
? PolicyAuthorizationResult.Forbid()
: PolicyAuthorizationResult.Challenge();
}
}
授權中介軟體委託它來實現身份驗證和授權處理,它內部會呼叫AuthorizationService,進而執行所有授權處理器AuthorizationHandler, (在後面會提到授權中介軟體用到這兩個方法)
3.7.1、AuthenticateAsync
當授權策略沒有設定AuthenticationSchemes,則只判斷下當前請求是否已做身份驗證,若做了就返回成功
當授權策略設定了AuthenticationSchemes,則遍歷身份驗證方案逐個進行身份驗證處理 。
其中context.User
就是使用context.AuthenticateAsync(DefaultAuthenticateScheme)
來賦值的,將所有得到的使用者標識重組成一個複合的使用者標識。
當我們希望使用非預設的Scheme,或者是想合併多個認證Scheme的Claims時,就需要使用基於Scheme的授權來重置Claims了。
它的實現也很簡單,直接使用我們在授權策略中指定的Schemes來依次呼叫認證服務的
AuthenticateAsync
方法,並將生成的Claims合併,最後返回我們熟悉的AuthenticateResult
認證結果。
3.7.2、AuthorizeAsync
該方法會根據Requirements來完成授權,具體的實現是通過呼叫IAuthorizationService
呼叫AuthorizeAsync
來實現的。
最終返回的是一個PolicyAuthorizationResult
物件,並在授權失敗時,根據認證結果來返回Forbid(未授權)
或Challenge(未登入)
。
以上彙總
- 授權服務IAuthorizationService,介面的預設實現為DefaultAuthorizationService,進行授權驗證。
- 在會根據授權策略提供器
IAuthorizationPolicyProvider
來獲取指定名稱的授權。- 通過授權處理器上下文物件工廠IAuthorizationHandlerContextFactory授權處理器AuthorizationHandler在授權時需要傳入AuthorizationHandlerContext(上面說了授權完成後的結果也儲存在裡面)。所以在執行授權處理器之前需要構建這個上下文物件,就是通過這個工廠構建的,主要的資料來源就是 當前 或者 指定的 授權策略AuthorizationPolicy。
- 所以這個時候會授權處理提供其 IAuthorizationHandlerProvider,來獲取系統中所有授權處理器。
- 授權評估器IAuthorizationEvaluator來確定授權結果是否成功,在授權處理器AuthorizationHandler在執行完授權後,結果是儲存在AuthorizationHandlerContext中的,這裡的評估器只是根據AuthorizationHandlerContext建立一個授權結果AuthorizationResult。
- 上面所說的授權處理器就是IAuthorizationHandler,處理器中包含主要的授權邏輯,在處理的過程中會將所有的授權處理器一一驗證。
- 所以在授權中介軟體中會利用IPolicyEvaluator中實現的身份認證和授權處理方法來呼叫AuthorizationService來執行所有的處理器。
四、中介軟體
在Configure中註冊管道:執行使用呼叫方法來配置Http請求管道
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ app.UseRouting();
//開啟認證授權
app.UseAuthentication();
app.UseAuthorization();
}
在這裡使用了授權中介軟體來檢查授權,來看看中介軟體的原始碼AuthorizationMiddleware
public class AuthorizationMiddleware
{
// Property key is used by Endpoint routing to determine if Authorization has run
private const string AuthorizationMiddlewareInvokedWithEndpointKey = "__AuthorizationMiddlewareWithEndpointInvoked";
private static readonly object AuthorizationMiddlewareWithEndpointInvokedValue = new object();
private readonly RequestDelegate _next;
private readonly IAuthorizationPolicyProvider _policyProvider;
public AuthorizationMiddleware(RequestDelegate next, IAuthorizationPolicyProvider policyProvider)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_policyProvider = policyProvider ?? throw new ArgumentNullException(nameof(policyProvider));
}
public async Task Invoke(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var endpoint = context.GetEndpoint();
if (endpoint != null)
{
context.Items[AuthorizationMiddlewareInvokedWithEndpointKey] = AuthorizationMiddlewareWithEndpointInvokedValue;
}
var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();
var policy = await AuthorizationPolicy.CombineAsync(_policyProvider, authorizeData);
if (policy == null)
{
await _next(context);
return;
}
var policyEvaluator = context.RequestServices.GetRequiredService<IPolicyEvaluator>();
var authenticateResult = await policyEvaluator.AuthenticateAsync(policy, context);
// Allow Anonymous skips all authorization
if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null)
{
await _next(context);
return;
}
// Note that the resource will be null if there is no matched endpoint
var authorizeResult = await policyEvaluator.AuthorizeAsync(policy, authenticateResult, context, resource: endpoint);
if (authorizeResult.Challenged)
{
if (policy.AuthenticationSchemes.Any())
{
foreach (var scheme in policy.AuthenticationSchemes)
{
await context.ChallengeAsync(scheme);
}
}
else
{
await context.ChallengeAsync();
}
return;
}
else if (authorizeResult.Forbidden)
{
if (policy.AuthenticationSchemes.Any())
{
foreach (var scheme in policy.AuthenticationSchemes)
{
await context.ForbidAsync(scheme);
}
}
else
{
await context.ForbidAsync();
}
return;
}
await _next(context);
}
}
進行程式碼分解:
- 拿到當前請求的的終結點
var endpoint = context.GetEndpoint();
- 在當前請求拿到終結點
endpoint
的時候,會通過終結點拿到關聯的IAuthorizeData
集合
var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();
- 將根據
IAuthorizeData
集合呼叫AuthorizationPolicy.CombineAsync()來建立組合策略(具體了可以看一下上一章) ( 用例: [Authorize(Policy = "BaseRole")] )
var policy = await AuthorizationPolicy.CombineAsync(_policyProvider, authorizeData);
IPolicyEvaluator
獲取策略評估器對得到的組合策略進行身份驗證,多種身份驗證得到的使用者證件資訊會合並進HttpContext.User
var policyEvaluator = context.RequestServices.GetRequiredService<IPolicyEvaluator>();
var authenticateResult = await policyEvaluator.AuthenticateAsync(policy, context);
- 當使用
[AllowAnonymous]
的時候,則直接跳過授權檢驗。
if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null)
{
await _next(context);
return;
}
- 將
IPolicyEvaluator
提供的AuthorizeAsync
授權檢查方法,進行策略授權檢查。
var authorizeResult = await policyEvaluator.AuthorizeAsync(policy, authenticateResult, context, resource: endpoint);
- 當進行授權時,遍歷策略所有的身份驗證方案,進行質詢,若策略裡木有身份驗證方案則使用預設身份驗證方案進行質詢。
當授權評估拒絕就直接呼叫身份驗證方案進行拒絕。
if (authorizeResult.Challenged)
{
if (policy.AuthenticationSchemes.Any())
{
foreach (var scheme in policy.AuthenticationSchemes)
{
await context.ChallengeAsync(scheme);
}
}
else
{
await context.ChallengeAsync();
}
return;
}
else if (authorizeResult.Forbidden)
{
if (policy.AuthenticationSchemes.Any())
{
foreach (var scheme in policy.AuthenticationSchemes)
{
await context.ForbidAsync(scheme);
}
}
else
{
await context.ForbidAsync();
}
return;
}
整個過程中,授權中介軟體會呼叫授權服務IAuthorizationService
來進行授權處理
五、總結
- 通過對上述的處理流程的分析,可以看出授權主要是通過
IAuthorizationService
來實現的,而我們進行使用只需要提供授權策略的Requirement,非常方便靈活的使用。 - 從原始碼許可權設計來看,系統註冊了各種服務,實現多種預設服務,加上預設的處理方式也滿足了大部分應用需求, 所以可以看出這一塊的功能還是很強大的,就算我們想通過自定義的方式來實現,也可以通過某些介面來實現擴充。
- 其中有很多核心原始碼怕說的不夠清楚,所以在平時的開發專案中,再去看官方文件或原始碼這樣理解應該更容易。
- 如果有不對的或不理解的地方,希望大家可以多多指正,提出問題,一起討論,不斷學習,共同進步。
- 參考的文件 和官方原始碼