Doubts about Sessions and Roles

Asked

Viewed 44 times

2

I have a controller responsible for doing the Login part, configured on web.config to use the

<authentication mode="Forms">
  <forms loginUrl="~/Usuario/Login" timeout="30" protection="All" path="/" />
</authentication>

And I wish only in a few ActionResult was accessed by some specific users, I saw that the [Authorize(Roles="exemplo")] meets my need, but I don’t know how I can make the code to create the profiles sessions for users, for example, administrator profile, client profile, etc. To be able to put in my Roles. I am using the Entity Framework and the MVC standard.

Could someone help me?

1 answer

2


  1. In the controller folder, find ManageController. Inside this, find and click on ApplicationUserManager and tighten F12. Will open the class IdentiyConfig.
  2. Above this class where you ended up, add the following code:

    public class ApplicationRoleManager : RoleManager<IdentityRole>
        {
            public ApplicationRoleManager(IRoleStore<IdentityRole, string> store)
                : base(store)
            {
            }
            public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> 
                   options, IOwinContext context)
            {
                var manager = new ApplicationRoleManager(new RoleStore<IdentityRole> 
                       (context.Get<ApplicationDbContext>()));
                return manager;
            }
        }
    
  3. Now, in the briefcase App_Start, open the class Startup.Auth and below this line app.CreatePerOwinContext<ApplicationSignInManager>ApplicationSignInManager.Create)

    Add this code:

     app.CreatePerOwinContext<ApplicationRoleManager>ApplicationRoleManager.Create);
    
  4. Go back to the ManagerController and below that

    private ApplicationUserManager _userManager;
    

    Add this:

    private ApplicationRoleManager _roleManager;
    
  5. Below the constructor, create the following:

    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }
    
  6. In the constructor that has 2 parameters, add one more parameter:

    public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, ApplicationRoleManager roleManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
        RoleManager = roleManager;
    }
    
  7. Still inside the ManageController, create a ViewModel:

    (before the public class ManageController : Controller)

    public class RoleViewModel
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
    
  8. Create this ActionResult within the ManageController (List)

    public ActionResult Roles()
    {
        var roles = RoleManager.Roles.ToList();
        return View(roles.Select(x => new RoleViewModel() { Id = x.Id, Name = x.Name }));
    }
    
  9. Create the View of this kind as List and using the ViewModel previously created. Don’t forget to exchange Create for Createrole here:

    @Html.ActionLink("Create New", "CreateRole")
    
  10. Create this ActionResult within the ManageController (Register)

    public ActionResult CreateRole()
    {
        return View();
    }
    
    [HttpPost]
    public ActionResult CreateRole(RoleViewModel model)
    {
        if (RoleManager.RoleExists(model.Name))
        {
            //Retorna erro, informando que ja existe essa Role
        }
        var newRole = new IdentityRole(model.Name);
        var result = RoleManager.Create(newRole);
    
        if (result.Succeeded)
        {
            return RedirectToAction("Roles");
        }
        return View(model);
    }
    
  11. Create the View of this kind as Create and using the ViewModel previously created.

  12. Create this ActionResult within the ManageController (Add Role to User)

    public ActionResult AddRoleToUser()
    {
        return View();
    }
    
    [HttpPost]
    public ActionResult AddRoleToUser(string user, string role)
    {
        var _user = UserManager.FindByEmail(user);
        var _role = RoleManager.FindByName(role);
        var result = UserManager.AddToRole(_user.Id, role);
    
        if (result.Succeeded)
        {
            return RedirectToAction("Roles");
        }
        ViewBag.Erro = result.Errors;
        return View();
    }
    
  13. Create the View of this kind as Create and using the ViewModel created earlier. Let’s make some changes to this View: Change the fields of the form:

<div class="form-group">
    @Html.Label("Usuario", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.Editor("user", new { htmlAttributes = new { @class = "form-control" } })
    </div>

    @Html.Label("Role", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.Editor("role", new { htmlAttributes = new { @class = "form-control" } })
    </div>
</div>

  1. Still inside this View, create the view of ViewBag.Erro:

@{
    ViewBag.Title = "AddRoleToUser";
    var erros = ViewBag.Erro as IEnumerable<String>;
}

<h2>AddRoleToUser</h2>

<ul>
    @foreach (var item in erros)
    {
        <li>@item</li>
    }
</ul>

  1. To finish, add the annotation to the View who wishes to check the roll:

    [Authorize(Roles = "RoleQueCriar")]
    public ActionResult Pagina(){ return View(); }
    

I learned that in this video and until today I do this way!!

Source: https://www.youtube.com/watch?v=ylmHZwAl9Hc

Browser other questions tagged

You are not signed in. Login or sign up in order to post.