ASP.NET MVC5 身份实现

ASP.NET MVC5 Identity Implementation

我一直致力于 MVC4 EF6 Web 应用程序项目,该项目使用简单的成员资格来确保 Web 安全,我希望一些用户可以访问某些网页并限制其他人访问。我刚刚发现 MVC5 提供了 EntityFrameWork.Identity,它可以满足我的需求 [Authorize(Roles=admin)]。所以我启动了一个 MVC 5 项目并复制了我的模型、上下文、视图和视图模型,一切似乎都在工作。

我在网上看到我需要更改我的用户 class 以从身份用户派生以支持 UserRoles 等。

因为我的原始用户 class 使用 public bool IsAdministrator { get; set; } 来区分管理员和用户,但身份为您提供了一个 AspNetUserRoles table 来做到这一点。我需要执行哪些步骤才能使用 [Authorize(Roles=admin)] 将某些控制器限制为某些用户?我一直在关注 http://johnatten.com/2014/06/22/asp-net-identity-2-0-customizing-users-and-roles/,但所有的应用程序管理器、DBcontext 配置、声明和存储都让我感到困惑。

IdentityModels.cs

public class ApplicationUser : IdentityUser
{        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    public int UserID { get; set; }

    public bool IsAdministrator { get; set; }
    [StringLength(50, MinimumLength = 1)]
    public string LastName { get; set; }
    [StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")]

    [Column("FirstName")]
    public string FirstMidName { get; set; }

    public string FullName
    {
        get { return FirstMidName + " " + LastName; }
    }
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime EnrollmentDate { get; set; }

    public int DepartmentID { get; set; }
    [ForeignKey("DepartmentID")]
    public virtual Department Department { get; set; }
    public int DepotID { get; set; }
    [ForeignKey("DepotID")]
    public virtual Depot Depot { get; set; }
    public virtual ICollection<Ticket> Tickets { get; set; }

}

Ticket.cs

public enum Priority
{
    Low, Med, High
}
public class Ticket
{
    public int? TicketID { get; set; }
    [Required(ErrorMessage = "Please enter the description")]
    public string Issue { get; set; }
    [Display(Name = "Administrator")]
    [Required(ErrorMessage = "Please select the Administrator")]
    public int IssuedTo { get; set; }
    public int Author { get; set; }

    [DisplayFormat(NullDisplayText = "No Priority")]
    public Priority Priority { get; set; }
    [ForeignKey("CategoryID")]
    public virtual Category Category { get; set; }
    public int CategoryID { get; set; }
    public int UserID { get; set; }
    [ForeignKey("UserID")]
    public virtual User User { get; set; }
}

Depot.cs

public class Depot
{
    public int DepotID { get; set; }
    [StringLength(50, MinimumLength = 1)]
    public string DepotName { get; set; }
    public virtual ICollection<User> Users { get; set; }

}

Department.cs

public class Department
{

    public int DepartmentID { get; set; }

    [StringLength(50, MinimumLength = 1)]
    public string DepartmentName { get; set; }

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

Category.cs

public class Category
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public virtual ICollection<Ticket> Tickets { get; set; }
}

问题上下文(数据库上下文)

public class IssueContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Ticket> Tickets { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Department> Departments { get; set; }
    public DbSet<Depot> Depots { get; set; }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

    }
}

IdentityModel.cs

中的ApplicationContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

Configuration.cs(种子)

        var users = new List<User>
        {
            new User { FirstMidName = "Jason",   LastName = "Wan",
                EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1, DepotID = 1,IsAdministrator = true},
            new User { FirstMidName = "Andy", LastName = "Domagas",
                EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1,DepotID = 1,IsAdministrator = true},
            new User { FirstMidName = "Denis",   LastName = "Djohar",
                EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1 ,DepotID = 1,IsAdministrator = true },
            new User { FirstMidName = "Christine",   LastName = "West",
                EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 2, DepotID = 3,IsAdministrator = false},

        };
        users.ForEach(s => context.Users.AddOrUpdate(p => p.FirstMidName, s));
        context.SaveChanges();

        users.ForEach(s => context.Users.AddOrUpdate(p => p.LastName, s));
        context.SaveChanges();

首先您需要创建 ASP.Net 用户角色。如果您使用的是 CodeFirst 迁移,则在 Seed 方法中使用以下代码来创建用户角色。

context.Roles.AddOrUpdate(r => r.Name, new IdentityRole { Name = "Admin" });
context.SaveChanges();

然后创建一个 ApplicationUser 实例并保存。 (我希望你可以自己做。)然后你必须将你的应用程序用户添加到管理员角色。这是它的代码-

// var user  = new ApplicationUser(){};
// create user using UserManager
//Now add user to role
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
manager.AddToRole(user.Id, "Admin");

一切就绪。现在使用[Authorize(Roles="Admin")]上面的动作或你想授权的控制器。

希望这对你有用..!