TykiMikk
TykiMikk

Reputation: 1068

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. I've just found out that MVC5 offers EntityFrameWork.Identity which does what I want [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.

I read online that I need to change my User class to derive from Identity user to support UserRoles etc.

Since my original User class uses public bool IsAdministrator { get; set; } to differentiate from Admins and Users but Identity offers you a AspNetUserRoles table to do it. What steps do I need to do so that I can use [Authorize(Roles=admin)] to restrict certain controllers to certain users? 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.

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)

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

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

Configuration.cs(Seed)

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

Upvotes: 0

Views: 692

Answers (1)

SarangK
SarangK

Reputation: 690

At first you need to create the ASP.Net user role. If you are using CodeFirst Migration then use below code in Seed method to create user role.

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

Then create one ApplicationUser instance & save it. (I hope you can do this on your own.) then you have to add your Application user to Admin role. 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.

Hope this works for you..!

Upvotes: 1

Related Questions