AuthorizeAttribute 和AuthorizeFilter是怎麼樣的一個關係?他們跟中間件又是怎樣協同工作的?本文一起來探索Asp.Net Core 3.x 的源代碼,深入解讀他們的關係和中間件之間的那些你不知道的事。 ...
一、前言
IdentityServer4
已經分享了一些應用實戰的文章,從架構到授權中心的落地應用,也伴隨著對IdentityServer4
掌握了一些使用規則,但是很多原理性東西還是一知半解,故我這裡持續性來帶大家一起來解讀它的相關源代碼,本文先來看看為什麼Controller
或者Action
中添加Authorize
或者全局中添加AuthorizeFilter
過濾器就可以實現該資源受到保護,需要通過access_token
才能通過相關的授權呢?今天我帶大家來瞭解AuthorizeAttribute
和AuthorizeFilter
的關係及代碼解讀。
二、代碼解讀
解讀之前我們先來看看下麵兩種標註授權方式的代碼:
標註方式
[Authorize]
[HttpGet]
public async Task<object> Get()
{
var userId = User.UserId();
return new
{
name = User.Name(),
userId = userId,
displayName = User.DisplayName(),
merchantId = User.MerchantId(),
};
}
代碼中通過[Authorize]
標註來限制該api資源的訪問
全局方式
public void ConfigureServices(IServiceCollection services)
{
//全局添加AuthorizeFilter 過濾器方式
services.AddControllers(options=>options.Filters.Add(new AuthorizeFilter()));
services.AddAuthorization();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000"; //配置Identityserver的授權地址
options.RequireHttpsMetadata = false; //不需要https
options.ApiName = OAuthConfig.UserApi.ApiName; //api的name,需要和config的名稱相同
});
}
全局通過添加AuthorizeFilter
過濾器方式進行全局api資源的限制
AuthorizeAttribute
先來看看AuthorizeAttribute
源代碼:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AuthorizeAttribute : Attribute, IAuthorizeData
{
/// <summary>
/// Initializes a new instance of the <see cref="AuthorizeAttribute"/> class.
/// </summary>
public AuthorizeAttribute() { }
/// <summary>
/// Initializes a new instance of the <see cref="AuthorizeAttribute"/> class with the specified policy.
/// </summary>
/// <param name="policy">The name of the policy to require for authorization.</param>
public AuthorizeAttribute(string policy)
{
Policy = policy;
}
/// <summary>
/// 收取策略
/// </summary>
public string Policy { get; set; }
/// <summary>
/// 授權角色
/// </summary>
public string Roles { get; set; }
/// <summary>
/// 授權Schemes
/// </summary>
public string AuthenticationSchemes { get; set; }
}
代碼中可以看到AuthorizeAttribute
繼承了IAuthorizeData
抽象介面,該介面主要是授權數據的約束定義,定義了三個數據屬性
- Prolicy :授權策略
- Roles : 授權角色
- AuthenticationSchemes :授權Schemes 的支持
Asp.Net Core 中的http中間件會根據IAuthorizeData
這個來獲取有哪些授權過濾器,來實現過濾器的攔截並執行相關代碼。
我們看看AuthorizeAttribute
代碼如下:
public interface IAuthorizeData
{
/// <summary>
/// Gets or sets the policy name that determines access to the resource.
/// </summary>
string Policy { get; set; }
/// <summary>
/// Gets or sets a comma delimited list of roles that are allowed to access the resource.
/// </summary>
string Roles { get; set; }
/// <summary>
/// Gets or sets a comma delimited list of schemes from which user information is constructed.
/// </summary>
string AuthenticationSchemes { get; set; }
}
我們再來看看授權中間件
(UseAuthorization
)的核心代碼:
public static IApplicationBuilder UseAuthorization(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
VerifyServicesRegistered(app);
return app.UseMiddleware<AuthorizationMiddleware>();
}
代碼中註冊了AuthorizationMiddleware
這個中間件,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)
{
// EndpointRoutingMiddleware uses this flag to check if the Authorization middleware processed auth metadata on the endpoint.
// The Authorization middleware can only make this claim if it observes an actual endpoint.
context.Items[AuthorizationMiddlewareInvokedWithEndpointKey] = AuthorizationMiddlewareWithEndpointInvokedValue;
}
// 通過終結點路由元素IAuthorizeData來獲得對於的AuthorizeAttribute並關聯到AuthorizeFilter中
var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();
var policy = await AuthorizationPolicy.CombineAsync(_policyProvider, authorizeData);
if (policy == null)
{
await _next(context);
return;
}
// Policy evaluator has transient lifetime so it fetched from request services instead of injecting in constructor
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);
}
}
代碼中核心攔截並獲得AuthorizeFilter
過濾器的代碼
var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();
前面我分享過一篇關於 Asp.Net Core EndPoint 終結點路由工作原理解讀 的文章裡面講解到通過EndPoint
終結點路由來獲取Controller
和Action
中的Attribute
特性標註,這裡也是通過該方法來攔截獲取對於的AuthorizeAttribute
的.
而獲取到相關authorizeData
授權數據後,下麵的一系列代碼都是通過判斷來進行AuthorizeAsync
授權執行的方法,這裡就不詳細分享它的授權認證的過程了。
細心的同學應該已經發現上面的代碼有一個比較特殊的代碼:
if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null)
{
await _next(context);
return;
}
代碼中通過endpoint
終結點路由來獲取是否標註有AllowAnonymous
的特性,如果有則直接執行下一個中間件,不進行下麵的AuthorizeAsync
授權認證方法,
這也是為什麼Controller
和Action
上標註AllowAnonymous
可以跳過授權認證
的原因了。
AuthorizeFilter 源碼
有的人會問AuthorizeAttirbute
和AuthorizeFilter
有什麼關係呢?它們是一個東西嗎?
我們再來看看AuthorizeFilter
源代碼,代碼如下:
public class AuthorizeFilter : IAsyncAuthorizationFilter, IFilterFactory
{
/// <summary>
/// Initializes a new <see cref="AuthorizeFilter"/> instance.
/// </summary>
public AuthorizeFilter()
: this(authorizeData: new[] { new AuthorizeAttribute() })
{
}
/// <summary>
/// Initialize a new <see cref="AuthorizeFilter"/> instance.
/// </summary>
/// <param name="policy">Authorization policy to be used.</param>
public AuthorizeFilter(AuthorizationPolicy policy)
{
if (policy == null)
{
throw new ArgumentNullException(nameof(policy));
}
Policy = policy;
}
/// <summary>
/// Initialize a new <see cref="AuthorizeFilter"/> instance.
/// </summary>
/// <param name="policyProvider">The <see cref="IAuthorizationPolicyProvider"/> to use to resolve policy names.</param>
/// <param name="authorizeData">The <see cref="IAuthorizeData"/> to combine into an <see cref="IAuthorizeData"/>.</param>
public AuthorizeFilter(IAuthorizationPolicyProvider policyProvider, IEnumerable<IAuthorizeData> authorizeData)
: this(authorizeData)
{
if (policyProvider == null)
{
throw new ArgumentNullException(nameof(policyProvider));
}
PolicyProvider = policyProvider;
}
/// <summary>
/// Initializes a new instance of <see cref="AuthorizeFilter"/>.
/// </summary>
/// <param name="authorizeData">The <see cref="IAuthorizeData"/> to combine into an <see cref="IAuthorizeData"/>.</param>
public AuthorizeFilter(IEnumerable<IAuthorizeData> authorizeData)
{
if (authorizeData == null)
{
throw new ArgumentNullException(nameof(authorizeData));
}
AuthorizeData = authorizeData;
}
/// <summary>
/// Initializes a new instance of <see cref="AuthorizeFilter"/>.
/// </summary>
/// <param name="policy">The name of the policy to require for authorization.</param>
public AuthorizeFilter(string policy)
: this(new[] { new AuthorizeAttribute(policy) })
{
}
/// <summary>
/// The <see cref="IAuthorizationPolicyProvider"/> to use to resolve policy names.
/// </summary>
public IAuthorizationPolicyProvider PolicyProvider { get; }
/// <summary>
/// The <see cref="IAuthorizeData"/> to combine into an <see cref="IAuthorizeData"/>.
/// </summary>
public IEnumerable<IAuthorizeData> AuthorizeData { get; }
/// <summary>
/// Gets the authorization policy to be used.
/// </summary>
/// <remarks>
/// If<c>null</c>, the policy will be constructed using
/// <see cref="AuthorizationPolicy.CombineAsync(IAuthorizationPolicyProvider, IEnumerable{IAuthorizeData})"/>.
/// </remarks>
public AuthorizationPolicy Policy { get; }
bool IFilterFactory.IsReusable => true;
// Computes the actual policy for this filter using either Policy or PolicyProvider + AuthorizeData
private Task<AuthorizationPolicy> ComputePolicyAsync()
{
if (Policy != null)
{
return Task.FromResult(Policy);
}
if (PolicyProvider == null)
{
throw new InvalidOperationException(
Resources.FormatAuthorizeFilter_AuthorizationPolicyCannotBeCreated(
nameof(AuthorizationPolicy),
nameof(IAuthorizationPolicyProvider)));
}
return AuthorizationPolicy.CombineAsync(PolicyProvider, AuthorizeData);
}
internal async Task<AuthorizationPolicy> GetEffectivePolicyAsync(AuthorizationFilterContext context)
{
// Combine all authorize filters into single effective policy that's only run on the closest filter
var builder = new AuthorizationPolicyBuilder(await ComputePolicyAsync());
for (var i = 0; i < context.Filters.Count; i++)
{
if (ReferenceEquals(this, context.Filters[i]))
{
continue;
}
if (context.Filters[i] is AuthorizeFilter authorizeFilter)
{
// Combine using the explicit policy, or the dynamic policy provider
builder.Combine(await authorizeFilter.ComputePolicyAsync());
}
}
var endpoint = context.HttpContext.GetEndpoint();
if (endpoint != null)
{
// When doing endpoint routing, MVC does not create filters for any authorization specific metadata i.e [Authorize] does not
// get translated into AuthorizeFilter. Consequently, there are some rough edges when an application uses a mix of AuthorizeFilter
// explicilty configured by the user (e.g. global auth filter), and uses endpoint metadata.
// To keep the behavior of AuthFilter identical to pre-endpoint routing, we will gather auth data from endpoint metadata
// and produce a policy using this. This would mean we would have effectively run some auth twice, but it maintains compat.
var policyProvider = PolicyProvider ?? context.HttpContext.RequestServices.GetRequiredService<IAuthorizationPolicyProvider>();
var endpointAuthorizeData = endpoint.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();
var endpointPolicy = await AuthorizationPolicy.CombineAsync(policyProvider, endpointAuthorizeData);
if (endpointPolicy != null)
{
builder.Combine(endpointPolicy);
}
}
return builder.Build();
}
/// <inheritdoc />
public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (!context.IsEffectivePolicy(this))
{
return;
}
// IMPORTANT: Changes to authorization logic should be mirrored in security's AuthorizationMiddleware
var effectivePolicy = await GetEffectivePolicyAsync(context);
if (effectivePolicy == null)
{
return;
}
var policyEvaluator = context.HttpContext.RequestServices.GetRequiredService<IPolicyEvaluator>();
var authenticateResult = await policyEvaluator.AuthenticateAsync(effectivePolicy, context.HttpContext);
// Allow Anonymous skips all authorization
if (HasAllowAnonymous(context))
{
return;
}
var authorizeResult = await policyEvaluator.AuthorizeAsync(effectivePolicy, authenticateResult, context.HttpContext, context);
if (authorizeResult.Challenged)
{
context.Result = new ChallengeResult(effectivePolicy.AuthenticationSchemes.ToArray());
}
else if (authorizeResult.Forbidden)
{
context.Result = new ForbidResult(effectivePolicy.AuthenticationSchemes.ToArray());
}
}
IFilterMetadata IFilterFactory.CreateInstance(IServiceProvider serviceProvider)
{
if (Policy != null || PolicyProvider != null)
{
// The filter is fully constructed. Use the current instance to authorize.
return this;
}
Debug.Assert(AuthorizeData != null);
var policyProvider = serviceProvider.GetRequiredService<IAuthorizationPolicyProvider>();
return AuthorizationApplicationModelProvider.GetFilter(policyProvider, AuthorizeData);
}
private static bool HasAllowAnonymous(AuthorizationFilterContext context)
{
var filters = context.Filters;
for (var i = 0; i < filters.Count; i++)
{
if (filters[i] is IAllowAnonymousFilter)
{
return true;
}
}
// When doing endpoint routing, MVC does not add AllowAnonymousFilters for AllowAnonymousAttributes that
// were discovered on controllers and actions. To maintain compat with 2.x,
// we'll check for the presence of IAllowAnonymous in endpoint metadata.
var endpoint = context.HttpContext.GetEndpoint();
if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null)
{
return true;
}
return false;
}
}
代碼中繼承了 IAsyncAuthorizationFilter
, IFilterFactory
兩個抽象介面,分別來看看這兩個抽象介面的源代碼
IAsyncAuthorizationFilter
源代碼如下:
/// <summary>
/// A filter that asynchronously confirms request authorization.
/// </summary>
public interface IAsyncAuthorizationFilter : IFilterMetadata
{
///定義了授權的方法
Task OnAuthorizationAsync(AuthorizationFilterContext context);
}
IAsyncAuthorizationFilter
代碼中繼承了IFilterMetadata
介面,同時定義了OnAuthorizationAsync
抽象方法,子類需要實現該方法,然而AuthorizeFilter
中也已經實現了該方法,稍後再來詳細講解該方法,我們再繼續看看IFilterFactory
抽象介面,代碼如下:
public interface IFilterFactory : IFilterMetadata
{
bool IsReusable { get; }
//創建IFilterMetadata 對象方法
IFilterMetadata CreateInstance(IServiceProvider serviceProvider);
}
我們回到AuthorizeFilter
源代碼中,該源代碼中提供了四個構造初始化方法同時包含了AuthorizeData
、Policy
屬性,我們看看它的預設構造方法代碼
public class AuthorizeFilter : IAsyncAuthorizationFilter, IFilterFactory
{
public IEnumerable<IAuthorizeData> AuthorizeData { get; }
//預設構造函數中預設創建了AuthorizeAttribute 對象
public AuthorizeFilter()
: this(authorizeData: new[] { new AuthorizeAttribute() })
{
}
//賦值AuthorizeData
public AuthorizeFilter(IEnumerable<IAuthorizeData> authorizeData)
{
if (authorizeData == null)
{
throw new ArgumentNullException(nameof(authorizeData));
}
AuthorizeData = authorizeData;
}
}
上面的代碼中預設的構造函數預設給構建了一個AuthorizeAttribute
對象,並且賦值給了IEnumerable<IAuthorizeData>
的集合屬性;
好了,看到這裡AuthorizeFilter
過濾器也是預設構造了一個AuthorizeAttribute
的對象,也就是構造了授權所需要的IAuthorizeData
信息.
同時AuthorizeFilter
實現的OnAuthorizationAsync
方法中通過GetEffectivePolicyAsync
這個方法獲得有效的授權策略,並且進行下麵的授權AuthenticateAsync
的執行
AuthorizeFilter
代碼中提供了HasAllowAnonymous
方法來實現是否Controller
或者Action
上標註了AllowAnonymous
特性,用於跳過授權
HasAllowAnonymous
代碼如下:
private static bool HasAllowAnonymous(AuthorizationFilterContext context)
{
var filters = context.Filters;
for (var i = 0; i < filters.Count; i++)
{
if (filters[i] is IAllowAnonymousFilter)
{
return true;
}
}
//同樣通過上下文的endpoint 來獲取是否標註了AllowAnonymous特性
var endpoint = context.HttpContext.GetEndpoint();
if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null)
{
return true;
}
return false;
}
到這裡我們再回到全局添加過濾器的方式代碼:
services.AddControllers(options=>options.Filters.Add(new AuthorizeFilter()));
分析到這裡 ,我很是好奇,它是怎麼全局添加進去的呢?我打開源代碼看了下,源代碼如下:
public class MvcOptions : IEnumerable<ICompatibilitySwitch>
{
public MvcOptions()
{
CacheProfiles = new Dictionary<string, CacheProfile>(StringComparer.OrdinalIgnoreCase);
Conventions = new List<IApplicationModelConvention>();
Filters = new FilterCollection();
FormatterMappings = new FormatterMappings();
InputFormatters = new FormatterCollection<IInputFormatter>();
OutputFormatters = new FormatterCollection<IOutputFormatter>();
ModelBinderProviders = new List<IModelBinderProvider>();
ModelBindingMessageProvider = new DefaultModelBindingMessageProvider();
ModelMetadataDetailsProviders = new List<IMetadataDetailsProvider>();
ModelValidatorProviders = new List<IModelValidatorProvider>();
ValueProviderFactories = new List<IValueProviderFactory>();
}
//過濾器集合
public FilterCollection Filters { get; }
}
FilterCollection
相關核心代碼如下:
public class FilterCollection : Collection<IFilterMetadata>
{
public IFilterMetadata Add<TFilterType>() where TFilterType : IFilterMetadata
{
return Add(typeof(TFilterType));
}
//其他核心代碼為貼出來
}
代碼中提供了Add
方法,約束了IFilterMetadata
類型的對象,這也是上面的過濾器中為什麼都繼承了IFilterMetadata
的原因。
到這裡代碼解讀和實現原理已經分析完了,如果有分析不到位之處還請多多指教!!!
結論:授權中間件通過獲取IAuthorizeData
來獲取AuthorizeAttribute
對象相關的授權信息,並構造授權策略
對象進行授權認證的,而AuthorizeFilter
過濾器也會預設添加AuthorizeAttribute
的授權相關數據IAuthorizeData
並實現OnAuthorizationAsync
方法,同時中間件中通過授權策略提供者IAuthorizationPolicyProvider
來獲得對於的授權策略進行授權認證.