Right now I decorate a method like this to allow \"members\" to access my controller action
[Authorize(Roles=\"members\")]
How do I
Another clear solution, you can use constants to keep convention and add multiple [Authorize] attributes. Check this out:
public static class RolesConvention
{
public const string Administrator = "Administrator";
public const string Guest = "Guest";
}
Then in the controller:
[Authorize(Roles = RolesConvention.Administrator )]
[Authorize(Roles = RolesConvention.Guest)]
[Produces("application/json")]
[Route("api/[controller]")]
public class MyController : Controller
If you want use custom roles, you can do this:
CustomRoles
class:
public static class CustomRoles
{
public const string Administrator = "Administrador";
public const string User = "Usuario";
}
Usage
[Authorize(Roles = CustomRoles.Administrator +","+ CustomRoles.User)]
If you have few roles, maybe you can combine them (for clarity) like this:
public static class CustomRoles
{
public const string Administrator = "Administrador";
public const string User = "Usuario";
public const string AdministratorOrUser = Administrator + "," + User;
}
Usage
[Authorize(Roles = CustomRoles.AdministratorOrUser)]
If you find yourself applying those 2 roles often you can wrap them in their own Authorize. This is really an extension of the accepted answer.
using System.Web.Mvc;
public class AuthorizeAdminOrMember : AuthorizeAttribute
{
public AuthorizeAdminOrMember()
{
Roles = "members, admin";
}
}
And then apply your new authorize to the Action. I think this looks cleaner and reads easily.
public class MyController : Controller
{
[AuthorizeAdminOrMember]
public ActionResult MyAction()
{
return null;
}
}
Another option is to use a single authorize filter as you posted but remove the inner quotations.
[Authorize(Roles="members,admin")]
Intent promptInstall = new Intent(android.content.Intent.ACTION_VIEW);
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
promptInstall.setDataAndType(Uri.parse("http://10.0.2.2:8081/MyAPPStore/apk/Teflouki.apk"), "application/vnd.android.package-archive" );
startActivity(promptInstall);
Using AspNetCore 2.x, you have to go a little different way:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AuthorizeRoleAttribute : AuthorizeAttribute
{
public AuthorizeRoleAttribute(params YourEnum[] roles)
{
Policy = string.Join(",", roles.Select(r => r.GetDescription()));
}
}
just use it like this:
[Authorize(YourEnum.Role1, YourEnum.Role2)]