使用[Authorize]而不使用SimpleMembershipProvider

时间:2014-02-02 14:41:42

标签: c# asp.net-mvc entity-framework simplemembership

有没有办法使用......

[Authorize(Roles: "Administrator")]
public class SomeController : Controller
{
    ...
}

...使用我自己的Roles数据库表,而不使用SimpleMembershipProvider

我的UsersRoles模型类:

[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; }
}

有人有同样的问题吗?

2 个答案:

答案 0 :(得分:1)

您应该通过继承Authorize

来创建自己的AuthorizeAttribute属性
public class CustomAuthorizeAttribute : AuthorizeAttribute
{

}

然后你可以随意配置它。

您还可以在Stackoverflow上查看这些问题:

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

答案 1 :(得分:0)

我遇到了同样的问题,我使用了自定义属性。但我的角色并不那么复杂。我需要能够为用户提供多个角色,所以我只是使用字符串集合来做到这一点。我使用了这个自定义过滤器

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