2016-03-26 46 views
0

我一直在研究一個MVC4 EF6的Web應用程序項目,它使用簡單的成員資格進行Web安全性,我希望有些用戶可以訪問某些網頁和其他人的限制。我剛剛發現,MVC5提供EntityFrameWork.Identity,這是我想要的[Authorize(Roles = admin)]。所以我開始了一個MVC 5項目,並複製了我的模型,上下文,視圖和視圖模型,並且一切看起來都是一樣的。ASP.NET MVC5標識實現

我在線閱讀,我需要改變我的用戶類從用戶身份以獲得支持等的UserRole

因爲我原來的用戶類使用public bool IsAdministrator { get; set; }從管理員和用戶區分,但身份爲您提供AspNetUserRoles表做到這一點。我需要執行哪些步驟才能使用[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; } 
} 

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>(); 

    } 
} 

的ApplicationContext在IdentityModel.cs

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(); 

回答

1

在第一你n eed創建ASP.Net用戶角色。如果您正在使用CodeFirst Migration,則在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")]上面的動作或控制器,你想要授權。

希望這適用於你..!

+0

我的dbcontext如何。 IssueContext來自MVC4,現在我需要有人從applicationDBcontext派生它。我也在那裏添加了我的configuration.cs文件,並且在Roles和IdentityRole上有錯誤:'context.Roles.AddOrUpdate(r => r.Name,new IdentityRole {Name =「Admin」});' – TykiMikk

+0

@JasonWan I建議只使用ApplictionDbContext和所有設置的db。對於Configuration.cs確保你有引用[使用Microsoft.AspNet.Identity; 使用Microsoft.AspNet.Identity。的EntityFramework;] – SarangK