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
We have code base ready, we need to implement the wrapper class to handle the API request. Right-click on the solution and add a new class. Enter the class name and click on Add. Next Inherite Attribute, IAuthorizationFilter to CustomAuthorization class which has overridden the OnAuthorization method.
The Authorize Attribute This means that once the request matches a supported route and is resolved to controller and method, it gets executed no matter what. Put another way, any public method defined on the controller class can be run if only the user calls the right URL.
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 ;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With