Axelly
Axelly

Reputation: 859

How to check whether request is going to an method with [Authorize] attribute?

I have WebAPI Controller which derives from BaseController which derives from AspNetCore's Controller

I'd want to load User from database whenever he's going into endpoint which requires being [Authorize]

This is my code where condition in that if is pseudo code because I cannot figure out how to check whether this request requires authorization or it doesn't

public class DefaultController : Controller
{
    protected readonly DatabaseContext _context;
    protected readonly User _user;

    public DefaultController(DatabaseContext context)
    {
        _context = context;

        if (HttpContext.Request.RequiresAuthorization) // pseudo code
        {
            var id = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            _user = _context.Users.Find(id);
        }
    }
}

Basically I'd want to avoid loading user on every request, even when he does not need to authorize and can be not logged in there.

Is it possible to achieve kinda "globally", so BaseController which every other controller derives from?

Upvotes: 3

Views: 1860

Answers (1)

codeninja.sj
codeninja.sj

Reputation: 4119

You can use MvcOptions.Filters to register your authorization filter globally.

Startup.cs

public void ConfigureServices(IServiceCollection services)
 { 
      services.AddMvc(options =>
      {
           options.Filters.Add(typeof(AuthorizationFilter));
      });
 }

Since you have the requirement to connect a database, I would suggest, to create a custom AuthorizationFilter by extending IAsyncAuthorizationFilter

public class AuthorizationFilter : IAsyncAuthorizationFilter
{
    //use constructor to inject required dependencies

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
         //Move your custom logic here
    }
}

Upvotes: 2

Related Questions