天天看點

Asp.Net Core Authorize你不知道的那些事(源碼解讀)

Asp.Net Core Authorize你不知道的那些事(源碼解讀)

一、前言

IdentityServer4已經分享了一些應用實戰的文章,從架構到授權中心的落地應用,也伴随着對IdentityServer4掌握了一些使用規則,但是很多原理性東西還是一知半解,故我這裡持續性來帶大家一起來解讀它的相關源代碼,本文先來看看為什麼Controller或者Action中添加Authorize或者全局中添加AuthorizeFilter過濾器就可以實作該資源受到保護,需要通過access_token才能通過相關的授權呢?今天我帶大家來了解AuthorizeAttribute和AuthorizeFilter的關系及代碼解讀。

二、代碼解讀

解讀之前我們先來看看下面兩種标注授權方式的代碼:

标注方式

[Authorize]

[HttpGet]

public async Task

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() ?? Array.Empty();

前面我分享過一篇關于 Asp.Net Core EndPoint 終結點路由工作原了解讀 的文章裡面講解到通過EndPoint終結點路由來擷取Controller和Action中的Attribute特性标注,這裡也是通過該方法來攔截擷取對于的AuthorizeAttribute的.

而擷取到相關authorizeData授權資料後,下面的一系列代碼都是通過判斷來進行AuthorizeAsync授權執行的方法,這裡就不詳細分享它的授權認證的過程了。

細心的同學應該已經發現上面的代碼有一個比較特殊的代碼:

if (endpoint?.Metadata.GetMetadata() != 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源代碼如下:

///

/// A filter that asynchronously confirms request authorization.

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 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的集合屬性;

好了,看到這裡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

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

public IFilterMetadata Add<TFilterType>() where TFilterType : IFilterMetadata
    {
        return Add(typeof(TFilterType));
    }

    //其他核心代碼為貼出來           

代碼中提供了Add方法,限制了IFilterMetadata類型的對象,這也是上面的過濾器中為什麼都繼承了IFilterMetadata的原因。

到這裡代碼解讀和實作原理已經分析完了,如果有分析不到位之處還請多多指教!!!

結論:授權中間件通過擷取IAuthorizeData來擷取AuthorizeAttribute對象相關的授權資訊,并構造授權政策對象進行授權認證的,而AuthorizeFilter過濾器也會預設添加AuthorizeAttribute的授權相關資料IAuthorizeData并實作OnAuthorizationAsync方法,同時中間件中通過授權政策提供者IAuthorizationPolicyProvider來獲得對于的授權政策進行授權認證.

作者:Jlion

原文位址

https://www.cnblogs.com/jlion/p/12544205.html

繼續閱讀