Reputation: 5162
I am familiar with how to use Authorize header in single & multiple authorization scenarios but given the following intended changes in the code base, I cannot figure out how to implement this with cluttering up the class code with additional properties which are multiple authorizations.
I have the following AuthorizationLevel class
public class AuthorizationLevel
{
public static class Roles
{
public const string Admin = "Admin";
public const string Developer = "DevOps";
public const string OfficeManager = "OfficeManager";
public const string Customer = "Customer";
public const string Distributor = "Distributor";
public const string Registered = "Basic";
}
}
In the controller, if I didn't have this class I would do something like
[Authorize(Roles = "Admins, Customers")]
But I prefer to have a class defining all the roles so I could do something like
[Authorize(Roles = AuthorizationLevel.Roles.Admin, AuthorizationLevel.Roles.Customer)]
The problem is that in this scenario, the parameter expected after the comma is a policy, so I tried this .
[Authorize(Roles = $"{AuthorizationLevel.Roles.Admin}, {AuthorizationLevel.Roles.Customer}")]
Which the editor did not like and should've worked because that code should be creating a comma delimited string.
How can I (or can't I) use this class in this scenario, rather than having to create additional properties in the class that combine multiple levels, i.e.
public const string AdminCust = "Admin, Customer";
Upvotes: 0
Views: 566
Reputation: 169200
You could implemenent a custom attribute:
public class RolesAttribute : AuthorizeAttribute
{
public RolesAttribute(params string[] roles)
{
if (roles != null)
Roles = string.Join(",", roles);
}
}
Usage:
[Roles(AuthorizationLevel.Roles.Admin, AuthorizationLevel.Roles.Customer)]
Upvotes: 1