2012-05-25 93 views
0

DB中我有RoleUser实体具有一对多关系。构建ASP.NET MVC中的自定义授权

我想要做的是构建自定义授权过滤器。我见过的所有教程都使用默认的ASP.NET成员资格。我所知道的是我需要继承AuthorizationAttribute,但不知道我需要覆盖哪些方法以及如何实现它们。

public class UserAuth : AuthorizeAttribute 
{ 

} 

DB

角色

public class Role 
{ 
    [Key] 
    public int RoleID { get; set; } 

    [Required] 
    public int RolenameValue { get; set; } 

    [MaxLength(100)] 
    public string Description { get; set; } 

    // // // // // 

    public Rolename Rolename 
    { 
     get { return (ProjectName.Domain.Enums.Rolename)RolenameValue; } 
     set { RolenameValue = (int)value; } 
    } 

    public virtual ICollection<User> Users { get; set; } 
} 

用户

public class User 
{ 
    [Key] 
    public int UserID { get; set; } 

    [Required] 
    [MaxLength(30)] 
    public string Username { get; set; } 

    [Required] 
    [MinLength(5)] 
    public string Password { get; set; } 

    [Required] 
    [DataType(DataType.EmailAddress)] 
    public string Email { get; set; } 

    [MaxLength(30)] 
    public string FirstName { get; set; } 

    [MaxLength(50)] 
    public string LastName { get; set; } 

    [DataType(DataType.Date)] 
    public DateTime Birthdate { get; set; } 

    public int GenderValue { get; set; } 

    // // // // // // // 

    public Gender Gender 
    { 
     get { return (ProjectName.Domain.Enums.Gender)GenderValue; } 
     set { GenderValue = (int)value; } 
    } 

    public int RoleID { get; set; } 

    [ForeignKey("RoleID")] 
    public Role Role { get; set; } 

回答

6

你并不需要创建一个自定义属性。你可以使用现有的AuthoriseAttribute,但你应该做的是实现定制Principal类,它将使用你自己的DB角色。在你Principal类,你将实现IsInRole方法:

public bool IsInRole(string role) 
{ 
    if(this.Roles == null) 
     this.Roles = DependencyResolver.Current 
      .GetService<ISecurityService>() 
      .GetUserPermissions(this.Identity.Name); 

    return this.Roles.Any(p => p.Name == role); 
} 

你应该设置你的自定义Principal在Global.asax中

void OnPostAuthenticateRequest(object sender, EventArgs e) 
    { 
     // Get a reference to the current User 
     IPrincipal user = HttpContext.Current.User; 

     // If we are dealing with an authenticated forms authentication request   
     if (user.Identity.IsAuthenticated && user.Identity.AuthenticationType == "Forms") 
     { 
      // Create custom Principal 
      var principal = new MyCustomPrincipal(user.Identity); 

      // Attach the Principal to HttpContext.User and Thread.CurrentPrincipal 
      HttpContext.Current.User = principal; 
      System.Threading.Thread.CurrentPrincipal = principal; 
     } 
    } 
+0

+1,我做同样的方式,但我加载的所有角色通过'OnPostAtuthenticate'中的授权存储库。 – jgauffin

+0

如何实现MyCustomPrincipal? :P 编辑:我的意思是,如何正确实施它。只用'IsInRole()'? – Bip

+1

从'GenericPrincipal'派生(http://msdn.microsoft.com/en-us/library/system.security.principal.genericprincipal.aspx)或实现'IPrincipal'接口 –