Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 917
Axelly Avatar asked Oct 22 '25 04:10

Axelly


1 Answers

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
    }
}
like image 161
codeninja.sj Avatar answered Oct 23 '25 16:10

codeninja.sj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!