Is there a way to use...
[Authorize(Roles: "Administrator")]
public class SomeController : Controller
{
...
}
...with my own Roles
database table, without using SimpleMembershipProvider
?
My Users
and Roles
model classes:
[Table("Users")]
public class UserModel
{
[Key]
public Int32 ID { get; set; }
[Required]
public String Name { get; set; }
[Required]
public String Password { get; set; }
[Required]
public virtual RoleModel Role { get; set; }
}
[Table("Roles")]
public class RoleModel
{
[Key]
public Int32 ID { get; set; }
[Required]
public String Name { get; set; }
public virtual ICollection<UserModel> Users { get; set; }
}
Does someone have the same problem?
You should create your own Authorize
attribute by inheriting from AuthorizeAttribute
class
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
}
Then you can configure it however you like.
Also you can take a look at these questions on Stackoverflow:
- Custom Authorize Attribute
- ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)
I ran into the same problem and I used a custom attribute. But my roles weren't as sophisticated. I needed to be able to give multiple roles to a user so I just used a string collection to do that. I used this custom filter
CustomAuthorize(UserRole="AUTHORIZED_ROLE");
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public string UserRole { get; set; }
protected IUnitOfWork uow = new UnitOfWork();
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
var currentUser;//Get Current User
if(UserRole==currentUser.Role.Name)
{
return true;
}
return false;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{//redirect where you want to in case of not authorized.
controller = "Home",
action = "AccessDenied"
})
);
}