As the title says, I try to let the controller distinguish between two states.
- If a field "allowed" in appsettings is true, allow for unauthorized users to have access to the controller.
- If "allowed" is false, allow access just for authorized users.
But I'm not quiet understand how can I implement it using policies. Can I pass Boolean to an authorize attribute somehow?
Edit
Controller
[Authorize(Policy ="Unauthenticated")] // to pass here some additional argument
public string GetController();
In the Policy based Authorization Handler method, you could get the
allowed
value using the Configuration provider, then, according to the value to do the policy authorization or ignore the authorization.For example, based on this article, I have created a MinimumAgeHandler:
and the MinimumAgeRequirement:
Then, register the Authorization:
Add
"Allowed": true,
in the appsettings.json file.Finally, add Authorize attribute in the action method:
By using above sample code, after user login, if the
Allowed
isTrue
, it will ignore the MinimumAge validation.