Reputation: 96
Authorize attribute at PageModel is not enough because it applies to all handlers in that pagemodel. I am looking for some custom authorization lets say "Can access only if age is 18+", so how to implement same in RazorPages (Not MVC)? Is there any neat and clear solution for this??
Upvotes: 0
Views: 558
Reputation: 27578
Currently it is not possible to use Authorize
attribute on individual Razor Page handlers , you can trace the feature request in here .
As a workaround , you can inject the IAuthorizationService
and implement the authorization manually :
private readonly IAuthorizationService _authorizationService;
public IndexModel(ILogger<PrivacyModel> logger, IAuthorizationService authorizationService)
{
_logger = logger;
_authorizationService = authorizationService;
}
public async Task OnGet()
{
var isAuthorized = await _authorizationService.AuthorizeAsync(
User, "PolicyName");
if (!isAuthorized.Succeeded)
{
//not pass the authorzation
}
}
And create policy to check whether the value user's age claim is over 18 as shown here .
Upvotes: 1