ASP.NET MVC5身份实现

时间:2016-03-26 02:52:50

标签: c# asp.net-mvc entity-framework asp.net-identity

我一直致力于MVC4 EF6 Web应用程序项目,该项目使用简单的Web会员资格,我希望一些用户能够访问某些网页并限制其他人使用。我刚刚发现MVC5提供了EntityFrameWork.Identity,它可以满足我的需求[Authorize(Roles = admin)]。所以我开始了一个MVC 5项目并复制了我的模型,上下文,视图和视图模型,所有内容似乎都是一样的。

我在线阅读我需要更改我的User类以从Identity用户派生以支持UserRoles等。

由于我的原始用户类使用[Authorize(Roles=admin)]来区分管理员和用户,但Identity为您提供了一个AspNetUserRoles表。我需要执行哪些步骤才能使用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; } } 将某些控制器限制为某些用户?我一直关注http://johnatten.com/2014/06/22/asp-net-identity-2-0-customizing-users-and-roles/,但所有的应用程序管理器,DBcontext配置,声明和商店都让我感到困惑。

IdentityModels.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; }
}

Ticket.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; }

}

Depot.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; }
}

Department.cs

public class Category
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public virtual ICollection<Ticket> Tickets { get; set; }
}

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

    }
}

IssueContext(的DbContext)

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

IdentityModel.cs中的ApplicationContext

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

Configuration.cs(种子)

BufferedInputStream

1 个答案:

答案 0 :(得分:1)

首先,您需要创建ASP.Net用户角色。如果您正在使用CodeFirst Migration,请在Seed方法中使用以下代码来创建用户角色。

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

然后创建一个ApplicationUser实例&amp;保存。 (我希望您可以自己完成此操作。)然后您必须将您的Application用户添加到Admin角色。这是代码 -

// 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")]上面要进行授权的操作或控制器。

希望这对你有用..!