Kevin Krumwiede
Kevin Krumwiede

Reputation: 10308

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?

Upvotes: 0

Views: 448

Answers (1)

Ruikai Feng
Ruikai Feng

Reputation: 11896

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

Upvotes: 2

Related Questions