简体   繁体   English

ASP.NET MVC5身份实现

[英]ASP.NET MVC5 Identity Implementation

I've been working on a MVC4 EF6 web application project which uses simple membership for web security and I wanted some users to have access to some webpages and restrictions to others. 我一直在从事MVC4 EF6网络应用程序项目,该项目使用简单的成员资格来确保网络安全,我希望某些用户可以访问某些网页并对其他用户进行限制。 I've just found out that MVC5 offers EntityFrameWork.Identity which does what I want [Authorize(Roles=admin)]. 我刚刚发现MVC5提供了EntityFrameWork.Identity,它可以执行我想要的[Authorize(Roles = admin)]。 So I started a MVC 5 project and copied over my Models,Context,Views and Viewmodels and everything seems to be working the same. 因此,我开始了一个MVC 5项目,并复制了我的Models,Context,Views和Viewmodels,一切似乎都在正常运行。

I read online that I need to change my User class to derive from Identity user to support UserRoles etc. 我在线阅读了有关更改User类以从Identity用户派生以支持UserRoles等的信息。

Since my original User class uses public bool IsAdministrator { get; set; } 由于我的原始User类使用的是public bool IsAdministrator { get; set; } public bool IsAdministrator { get; set; } public bool IsAdministrator { get; set; } to differentiate from Admins and Users but Identity offers you a AspNetUserRoles table to do it. public bool IsAdministrator { get; set; }以区别于“管理员”和“用户”,但“身份”向您提供一个AspNetUserRoles表来执行此操作。 What steps do I need to do so that I can use [Authorize(Roles=admin)] to restrict certain controllers to certain users? 我需要执行哪些步骤才能使用[Authorize(Roles=admin)]将某些控制器限制为某些用户? I've been following http://johnatten.com/2014/06/22/asp-net-identity-2-0-customizing-users-and-roles/ but all the application manager, DBcontext configuration,Claims and Stores are so confusing to me. 我一直在关注http://johnatten.com/2014/06/22/asp-net-identity-2-0-customizing-users-and-roles/,但是所有应用程序管理器,DBcontext配置,声明和存储都在让我感到困惑。

IdentityModels.cs 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 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 仓库.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 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) 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 in IdentityModel.cs IdentityModel.cs中的ApplicationContext

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

Configuration.cs(Seed) 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();

At first you need to create the ASP.Net user role. 首先,您需要创建ASP.Net用户角色。 If you are using CodeFirst Migration then use below code in Seed method to create user role. 如果您使用的是CodeFirst Migration,则在Seed方法中使用以下代码创建用户角色。

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

Then create one ApplicationUser instance & save it. 然后创建一个ApplicationUser实例并保存。 (I hope you can do this on your own.) then you have to add your Application user to Admin role. (我希望您可以自己执行此操作。)然后必须将您的Application用户添加为Admin角色。 Here is the code for it- 这是它的代码-

// 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");

Here all set. 都准备好了 Now use [Authorize(Roles="Admin")] above action or Controller which you want to make authorize. 现在,在要授权的操作或控制器上使用[Authorize(Roles="Admin")]

Hope this works for you..! 希望这对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM