asp.net-coreauthorize-attribute

How does ASP.NET Core AuthorizeAttribute work under the hood?


ASP.NET Core AuthorizeAttribute is just a marker containing a little data and no behavior (source). Whatever visits the attribute must contain the behavior.

What visits AuthorizeAttribute and what does it do?


Solution

  • AuthorizeAttribute implemented IAuthorizeData interface

    public class AuthorizeAttribute : Attribute, IAuthorizeData
    

    app.UseAuthorization() middleware visits AuthorizeAttribute From endpoint metadata accroding to the source code:

    var endpoint = context.GetEndpoint();
    ......
    var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();
    

    then it could access the scheme,policy,roles you defined when you add the Authorize attribute

    You could try similar in a middleware:

    app.Use(async (context, next) =>
    {
        var endpoint = context.GetEndpoint();
        var authdata = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>();
        await next.Invoke();
    });
    

    Result:

    enter image description here