Doug
Doug

Reputation: 264

How do you check authorization in a class in ASP Core?

I am trying to access the IAuthorizationService inside a class, but can't figure out how.

Here's what I'm trying to do.

I have a JSON file with navigation items in it and the names of security policies that are attached to them. I want to validate a user has access to that policy to know whether or not to show or hide that item.

How can I get that injected so I have access to it to do something like this:

await (IAuthorizationService).AuthorizeAsync(user, PolicyName).Succeeded

Upvotes: 1

Views: 377

Answers (1)

Joe Audette
Joe Audette

Reputation: 36716

You should register your class with DI and take a constructor dependency on IAuthorizationService so it will be injected into your class

public YourClassConstructor(IAuthorizationService authService)
{
   _authService = authService;
}

private IAuthorizationService _authService;

public async Task SomeMethod()
{
    var result = await _authService.AuthorizeAsync(user, PolicyName);
    if(result.Succeeded) 
    {
       //...
    }
}

Then you need to wait for the result to come back before you can check .Succeeded

Upvotes: 4

Related Questions