Reputation: 33691
I'm trying to create my own [Authorize] Attribute so I can use my own authorize logic to have hierarchal roles.
If someone does [Authorize(Roles = "Admin")]
on a controller or action
How do I get the string "Admin" in my AuthorizeCore function?
I'm using this code:
public class Authorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//authorize role logic
if (true)
return true;
return false;
}
}
MVC4, .net 4.5, c#, VS 2012
Upvotes: 6
Views: 4970
Reputation: 9881
If you need to get the list of allowed roles, you can simply get the Roles property. It will list the string that was specified in the attribute decoration.
public class Authorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var allowedRoles = Roles;
}
}
You can see this on the AuthorizeAttribute definition
Upvotes: 0
Reputation: 16145
Roles is a public property. You should be able to do this:
public class Authorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if(Roles.Contains("MyRole"))
return true;
return false;
}
}
Or whatever it is that you need to do
Upvotes: 1
Reputation: 5843
It is quit a common thing that you have faced with.
This recommendation in post should work in MVC4 as it is working in MVC 3: - ASP.NET MVC - Alternative to Role Provider?
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool isAdmin;
if(Roles.Contains("Admin"))
isAdmin = true;
return isAdmin ;
}
Upvotes: 9