2016-03-26 9 views
0

私はMVC4 EF6 Webアプリケーションプロジェクトで作業していました。これは単純なメンバーシップをWebセキュリティに使用しています。一部のユーザーが一部のWebページにアクセスし、他のユーザーに制限を与えたいと思っていました。 MVC5がEntityFrameWork.Identityを提供していることがわかりました。[Authorize(Roles = admin)]を実行します。私はMVC 5プロジェクトを開始し、モデル、コンテキスト、ビュー、ビューモデルをコピーして、すべてが同じように動作しているようです。ASP.NET MVC5アイデンティティの実装

私の元のUserクラスは、管理者やユーザーから区別するためにpublic bool IsAdministrator { get; set; }を使用していますが、アイデンティティがにあなたAspNetUserRolesテーブルを提供していますので、私はなどUserRolesをサポートするために、アイデンティティユーザから導き出すために私のUserクラスを変更する必要があることをオンライン

を読みますそれをやる。 [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)IdentityModel.csで

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(シード)まず

 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 ASP.Netユーザーロールを作成します。 CodeFirst Migrationを使用している場合は、Seedメソッドで以下のコードを使用してユーザーロールを作成します。

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

は、次にそれを保存& 1つの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ファイルを追加しました。ロールとアイデンティティロールにエラーがあります: 'context.Roles.AddOrUpdate(r => r.Name、新しいIdentityRole {Name =" Admin "});' – TykiMikk

+0

@JasonWan I ApplictionDbContextのみを使用することをお勧めします。 Configuration.csについては、[Microsoft.AspNet.Identityを使用している参照があることを確認してください。 Microsoft.AspNet.Identityを使用しています。EntityFramework;] – SarangK

関連する問題