Using [Authorize] without SimpleMembershipProvider

2020-07-29 00:47发布

问题:

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?

回答1:

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:

  1. Custom Authorize Attribute
  2. ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)


回答2:

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" 
                        })
                    );
    }