2

DB私は1対多の関係を持つエンティティを持っRoleています。User

私がやろうとしているのは、カスタム認証フィルターを作成することです。私が見たすべてのチュートリアルは、デフォルトの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; }
4

1 に答える 1

7

カスタム属性を作成する必要はありません。既存の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);
}

PrincipalGlobal.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; 
        }
    } 
于 2012-05-25T12:04:32.330 に答える