简体   繁体   中英

Enabling specific authentication/authorization schemes on a per-endpoint basis

ASP.NET has the [Allow Anonymous] attribute which allows you to bypass authorization on a specific endpoint. I'm wondering if there's a common way of enabling specific authentication schemes on an endpoint by endpoint basis.

Imagine you wanted to support different schemes like a Basic scheme and a Bearer scheme and so on. But you didn't want to support all schemes on all endpoints. It seems like a convenient way to do that would be to create attributes like [BasicAuth] and [BearerAuth] so you could just annotate the specific endpoints you want to enable. Looking at how AuhtorizationAttributes work, however, it seems like they behave like a logical AND rather than a logical OR.

For example, if I annotated an endpoint with both [BasicAuth] and [BearerAuth] and one returns False on IsAuthorized the whole thing would fail. This makes me think I'm either looking in the wrong place or have an uncommon use-case.

Am I looking in the wrong direction?

AuthorizationAttribute supports different kind of authorizations. It can be used to support Policies or Roles . If you want an OR kind of logic you can use the authorization attribute with a comma separated string for roles. That will let your endpoint accessible by those roles.

Use it like this for OR logic:

[Authorize(Roles = "HRManager,Finance")]
public class SalaryController : Controller
{
}

For AND logic

[Authorize(Roles = "PowerUser")]
[Authorize(Roles = "ControlPanelUser")]
public class ControlPanelController : Controller
{
}

Source is Role-based authorization


I would recommend reading through the whole Authorization documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM