0

I am new to .net and have to create a project for school. I am using an MVC 5 template and it has a standard login but now I need 2 roles: student and teacher. How and where do I create those roles? And then how do I make it so that only logged in people can the last item from this nav

<div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li>@Html.ActionLink("Home", "Index", "Home")</li>
                <li>@Html.ActionLink("Roles", "Index", "Roles")</li>
                <li>@Html.ActionLink("Evaluaties", "About", "Home")</li>
            </ul>
            @Html.Partial("_LoginPartial")
        </div>

Plus I want one role to see a different view from the other how do I do that?

Burst of Ice
  • 386
  • 2
  • 6
  • 23

2 Answers2

4

MVC5 project template doesn't have role manager by default, so we start by creating our role manager classes; (in order to keep the project well structured it is better to add the classes as mentioned below):

1- create ApplicationRole class (add to IdentityModels.cs under Models folder)

public class ApplicationRole : IdentityRole
{
    public ApplicationRole() : base() { }

    public ApplicationRole(string name) : base(name) { }
}

2- create ApplicationRoleManager class (put it inside IdentityConfig.cs under App_Start folder)

public class ApplicationRoleManager : RoleManager<ApplicationRole>, IDisposable
{
    public ApplicationRoleManager(RoleStore<ApplicationRole> store) : base(store) { }

    public static ApplicationRoleManager Create(
        IdentityFactoryOptions<ApplicationRoleManager> options,
        IOwinContext context)
    {
        return new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
    }
}

3- configure the role manager at application start up; add the below line to the ConfigureAuth(IAppBuilder app) method in Startup.Auth.cs file :

app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

4- create a new controller if required or use an existing one, and define the parameters for ApplicationuserManager and ApplicationRoleManager inside the controller constructor, then retrieve the identity managers from the owin context:

    namespace UsersAndRoles.Controllers
{
using Microsoft.AspNet.Identity.Owin;
using System.Web;
using System.Web.Mvc;

    public class UsersAndRolesController : Controller
    {
        private ApplicationUserManager _userManager;
        private ApplicationRoleManager _roleManager;

        public UsersAndRolesController() { }

        public UsersAndRolesController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
        {
            UserManager = userManager;
            RoleManager = roleManager;
        }

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        public ApplicationRoleManager RoleManager
        {
            get
            {
                return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
            }
            private set
            {
                _roleManager = value;
            }
        }

        // GET: UsersAndRoles
        public ActionResult Index()
        {
            return View();
        }
    }
}

The setup is done now and the controller is ready to create users and roles, in order to create a user simply create an ApplicationUser and add it using UserManager.Create method, the password must match the rules defined in the ApplicationUserManager class.

5- create user by calling UserManager.Create method:

var user = new ApplicationUser
        {
            UserName = "Ziyad",
            Email = "email@domainname.com"
        };

        var password = "P@ssw0rd";
        UserManager.Create(user, password);

6- creating roles in a similar way using RoleManager:

var role = new ApplicationRole
        {
            Name = "Students"
        };

        RoleManager.Create(role);

7- last part is to assign roles to users using UserManager:

UserManager.AddToRole("user_id", "role_name");

the complete controller is here :

    namespace UsersAndRoles.Controllers
{
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.Owin;
    using System.Web;
    using System.Web.Mvc;
    using Models;
public class UsersAndRolesController : Controller
{
    private ApplicationUserManager _userManager;
    private ApplicationRoleManager _roleManager;

    public UsersAndRolesController() { }

    public UsersAndRolesController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
    {
        UserManager = userManager;
        RoleManager = roleManager;
    }

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

    public string CreateUser()
    {
        var user = new ApplicationUser
        {
            UserName = "Ziyad",
            Email = "email@domainname.com"
        };

        var password = "P@ssw0rd";
        var result = UserManager.Create(user, password);

        if (result.Succeeded)
        {
            return "User created";
        }
        else
        {
            var msg = "Error, user not created";
            foreach (var err in result.Errors)
                msg += err + "<br />";

            return msg;
        }            
    }

    public string CreateRole()
    {
        var role = new ApplicationRole
        {
            Name = "Teachers"
        };

        var result = RoleManager.Create(role);

        if (result.Succeeded)
        {
            return "Role created";
        }
        else
        {
            var msg = "Error, role not created";
            foreach (var err in result.Errors)
                msg += err + "<br />";

            return msg;
        }
    }

    public string AddUserToRole()
    {
        var user = UserManager.FindByEmail("email@domainname.com");

        if (user != null)
        {
            var result = UserManager.AddToRole(user.Id, "Teachers");
            if (result.Succeeded)
            {
                return "User assigned to role";
            }
            else
            {
                var msg = "Error, user not assigned to role <br />";
                foreach (var err in result.Errors)
                    msg += err + "<br />";

                return msg;
            }
        }
        else
        {
            return "User not found!";
        }
    }
}

}

if you want to restrict some views/menus to specific roles use User.IsInRole("role_name") method:

if (User.IsInRole("Teachers"))
        {
            // role specific options
        }

if you want to allow only specific role to access an action method use the authorize attribute:

[Authorize(Roles = "Teachers")]
public ActionResult ActionName()
{
    //teachers specific method
}

hope this helps :)

LazZiya
  • 5,286
  • 2
  • 24
  • 37
0

You can save the roles in the database and after the user is successfully logged in, you can add the roles in authentication cookie. Please see my answer here.

Community
  • 1
  • 1
Akshay
  • 530
  • 7
  • 20