asp.net core check route attribute in middleware

Viewed 7836

I'm trying to build some ASP.Net core middleware.

It needs see if the current route is marked as [Authorize].

eg:

public async Task Invoke(HttpContext context)
{
    if(context.Request.Path.Value.StartsWith("/api"))
    {
        // check if route is marked as [Authorize]
        // and then do some logic
    }

    await _next.Invoke(context);
}

Does anyone know how this could be achieved or if it's even possible?

If not, what would be a good alternative approach?

4 Answers

I believe it can be achieved in a middleware class via:

var hasAuthorizeAttribute = context.Features.Get<IEndpointFeature>().Endpoint.Metadata
                .Any(m => m is AuthorizeAttribute);

HansElsen's answer is correct, but I would like to add some things to note about it:

  1. You can use the extension method context.GetEndpoint() which is exactly the same as context.Features.Get<IEndpointFeature>().Endpoint
  2. The endpoint will always be null if you set up your middleware before calling app.UseRouting() in your Startup.cs:

Don't do:

app.UseMiddleware<MyMiddleware>();
app.UseRouting();

Do:

app.UseRouting();
app.UseMiddleware<MyMiddleware>();
Related