2016-03-26 29 views
0

Web güvenliği için basit üyeliği kullanan bir MVC4 EF6 web uygulaması projesi üzerinde çalışıyorum ve bazı kullanıcıların bazı web sayfalarına ve başkalarına yönelik kısıtlamalara erişmesini istedim. MVC5'in istediğim şeyi yapan EntityFrameWork.Identity'yi sunduğunu öğrendim [Authorize (Roles = admin)]. Bu yüzden bir MVC 5 projesine başladım ve Modellerim, Bağlamım, Görünümler ve Görünüm Modellerimin üzerine kopyaladım ve her şey aynı şekilde çalışıyor gibi görünüyor. ASP.NET MVC5 Kimlik Uygulaması

Ben vs. UserRoles desteklemek için Kimlik kullanıcıdan türetmek için benim Kullanıcı sınıfını değiştirmek gerekir çevrimiçi okumak

benim orijinal Kullanıcı sınıfı Yöneticiler ve Kullanıcılardan ayırt etmek public bool IsAdministrator { get; set; } kullanır ama Kimlik size bir AspNetUserRoles tablosunu sunuyor yana yap. Belirli denetleyicileri belirli kullanıcılarla kısıtlamak için [Authorize(Roles=admin)] kullanabilmem için hangi adımları uygulamam gerekiyor? http://johnatten.com/2014/06/22/asp-net-identity-2-0-customizing-users-and-roles/'u takip ediyorum ancak tüm uygulama yöneticisi, DBcontext konfigürasyonu, Talepler ve Mağazalar bana çok kafa karıştırıcı.

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) IdentityModel.cs içinde

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

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

Configuration.cs (tohum) Başta

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

cevap

1

sen n ASP.Net kullanıcı rolünü oluşturmak için eed. CodeFirst Migration kullanıyorsanız, kullanıcı rolü oluşturmak için Seed yönteminde aşağıdaki kodu kullanın.

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

Sonra kaydetmek & bir ApplicationUser örneği oluşturun. (Umarım bunu kendi başınıza yaparsınız.) Daha sonra, Uygulama kullanıcınızı Yönetici rolüne eklemelisiniz. İşte burada tüm set. Şimdi yetkilendirmek istediğiniz eylem veya Denetleyici'nin yukarıdaki [Authorize(Roles="Admin")] kullanın.

Bu sizin için çalışır umuyoruz ..!

+0

Nasıl dbcontext'im hakkında. IssueContext MVC4'ten oldu ve şimdi birisini applicationDBcontext'ten türetmem gerekiyor. Ayrıca benim config.cs dosyasımı ekledim ve Roles ve IdentityRole: 'context.Roles.AddOrUpdate (r => r.Name, new IdentityRole {Name =" Admin "}); – TykiMikk

+0

@JasonWan I ApplictionDbContext'i ve sadece tüm db setlerini kullanmanızı öneririz. Configuration.cs için referanslara sahip olduğunuzdan emin olun [Microsoft.AspNet.Identity kullanarak; Microsoft.AspNet.Identity kullanarak .EntityFramework] – SarangK