簡體   English   中英

在ASP.NET MVC中構建CustomAuthorization

[英]Building CustomAuthorization in ASP.NET MVC

DB我具有具有一對多關系的RoleUser實體。

我想做的是建立自定義授權過濾器。 我看過的所有教程都使用默認的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; }

您無需創建自定義屬性。 您可以使用現有的AuthoriseAttribute但您應該做的是實現自定義Principal類,該類將使用您自己的數據庫角色。 在您的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);
}

您應該在Global.asax中設置自定義Principal

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM