我一直在开发一个MVC4 EF6 web应用程序项目,该项目使用简单的成员身份来实现web安全,我希望一些用户能够访问某些网页,并限制其他用户。我刚刚发现MVC5提供了EntityFrameWork.Identity,它做了我想要的事情[Authorize(Roles=admin)]。所以我开始了一个MVC 5项目,并复制了我的模型、上下文、视图和视图模型,一切似乎都一样。
我在网上读到,我需要更改我的User类以从Identity User派生,以支持UserRoles等。
由于我最初的User类使用public bool IsAdministrator { get; set; }
来区分Admins和Users,但Identity为您提供了一个AspNetUserRoles表。我需要执行哪些步骤才能使用[Authorize(Roles=admin)]
将某些控制器限制为某些用户?我一直在关注http://johnatten.com/2014/06/22/asp-net-identity-2-0-customizing-users-and-roles/但是所有的应用程序管理器、DBcontext配置、Claims和Stores都让我很困惑
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; }
}
部门.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; }
}
类别.cs
public class Category
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
IssueContext(dbcontext)
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")]
操作或您想要授权的控制器。
希望这对你有用。。!