【问题标题】:ASP.NET MVC5 Identity ImplementationASP.NET MVC5 身份实现
【发布时间】:2016-03-26 02:52:50
【问题描述】:

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

我在网上看到我需要更改我的 User 类以从 Identity 用户派生以支持 UserRoles 等。

由于我最初的 User 类使用 public bool IsAdministrator { get; set; } 来区分 Admins 和 Users,但 Identity 为您提供了一个 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; }
}

仓库.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; }
}

问题上下文(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>();

    }
}

IdentityModel.cs 中的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();

【问题讨论】:

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


    【解决方案1】:

    首先您需要创建 ASP.Net 用户角色。如果您使用 CodeFirst 迁移,请在 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")]上面你想要授权的action或Controller。

    希望这对你有用..!

    【讨论】:

    • 我的 dbcontext 怎么样。 IssueContext 来自 MVC4,现在我需要有人从 applicationDBcontext 派生它。我还在那里添加了我的 configuration.cs 文件,并且 Roles 和 IdentityRole 有错误:context.Roles.AddOrUpdate(r =&gt; r.Name, new IdentityRole { Name = "Admin" });
    • @JasonWan 我建议仅使用 ApplictionDbContext 并在其中设置所有所有数据库。对于 Configuration.cs,请确保您有参考资料 [使用 Microsoft.AspNet.Identity;使用 Microsoft.AspNet.Identity.EntityFramework;]
    猜你喜欢
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    相关资源
    最近更新 更多