Roles and Permits MVC 5

0

Good morning

I am working on a project with MVC 5 with Entity Framework, as you know the tables for the registration of users and roles are generated automatically is very easy with entity framework, well what I want to do is the customization of the permissions that must have the user.

At the moment I am resolving with the following:

@if (User.IsInRole("Administrador"))

 {

    <script>
            $('#Gestion').toggle();
            $('#Clientes').toggle();

    </script>
    }

 @if (User.IsInRole("Solicitud"))

        {
        <script>
            $('#Gestion').toggle();
            $('#Clientes').hide();
        </script>
  }

This validation is done from the view.

Also valid from the controller that the user must be logged in

public ActionResult Create()

    {

        var estaAutemticado = User.Identity.IsAuthenticated;
        if (estaAutemticado == true)
        {
            return View();
        }
        else
        {
            return RedirectToAction("Index", "Home");

            // return null;
        }

    }

is working for me because I can add new users and give them the permissions that I have validated in the view but it is static, I want to do something dynamic.

axis: the project is already finished and in production and they ask me to add a user who will only have permissions to register clients, he would have to modify the project.

I want to give the permissions from the database. create a table of permissions has PermisoID, Module, description the field module refers to the view I have in the controller.

I need help to do that part, that the logged in user only has access to the permissions that he has in that table, or if they know another way.

    
asked by SOTELO 01.12.2017 в 17:17
source

1 answer

1

Hi SOTELO first of all it is necessary to understand one thing: It is not the same Authentication that Authorization said that I explain how you can get the most out of Identity because as you say at the beginning you have created the tables of Usuarios , Roles and Rolesusuarios respectively when creating the project, this is due to the fact that you use the individual user authentication in your database using Identity . Let's go to the important thing. Suppose you have a controller called ClientesController .

namespace WebApp1.Controllers
{
[Authorize]
public class ClientesController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: /Clientes/
    public ActionResult Index()
    {
        return View(db.Clientes.ToList());
    }

    // GET: /Clientes/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Cliente cliente = db.Clientes.Find(id);
        if (cliente == null)
        {
            return HttpNotFound();
        }
        return View(cliente);
    }

    // GET: /Clientes/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: /Clientes/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="Id,Nombre,Edad,Empresa")] Cliente cliente)
    {
        if (ModelState.IsValid)
        {
            db.Clientes.Add(cliente);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(cliente);
    }

    // GET: /Clientes/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Cliente cliente = db.Clientes.Find(id);
        if (cliente == null)
        {
            return HttpNotFound();
        }
        return View(cliente);
    }

    // POST: /Clientes/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include="Id,Nombre,Edad,Empresa")] Cliente cliente)
    {
        if (ModelState.IsValid)
        {
            db.Entry(cliente).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(cliente);
    }

    // GET: /Clientes/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Cliente cliente = db.Clientes.Find(id);
        if (cliente == null)
        {
            return HttpNotFound();
        }
        return View(cliente);
    }

    // POST: /Clientes/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Cliente cliente = db.Clientes.Find(id);
        db.Clientes.Remove(cliente);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

}

Look at what I put on top of the Customers [Authorize] driver when declaring this Identity means that anyone who tries to enter the Customers driver must be authenticated. example if we run the project and put in the url localhost: port / clients / ****, if we are not logged in identity redirects us to the Login, here is an example of Authentication. Now let's look at an example of Role-Based Authorization that adapts very well to what you need.

[Authorize]
public class ClientesController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: /Clientes/
    public ActionResult Index()
    {
        return View(db.Clientes.ToList());
    }

    // GET: /Clientes/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Cliente cliente = db.Clientes.Find(id);
        if (cliente == null)
        {
            return HttpNotFound();
        }
        return View(cliente);
    }

    // GET: /Clientes/Create
    [Authorize(Roles="Administrador")]
    public ActionResult Create()
    {
        return View();
    }

    // POST: /Clientes/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [Authorize(Roles="Administrador")]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="Id,Nombre,Edad,Empresa")] Cliente cliente)
    {
        if (ModelState.IsValid)
        {
            db.Clientes.Add(cliente);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(cliente);
    }

    // GET: /Clientes/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Cliente cliente = db.Clientes.Find(id);
        if (cliente == null)
        {
            return HttpNotFound();
        }
        return View(cliente);
    }

    // POST: /Clientes/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include="Id,Nombre,Edad,Empresa")] Cliente cliente)
    {
        if (ModelState.IsValid)
        {
            db.Entry(cliente).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(cliente);
    }

    // GET: /Clientes/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Cliente cliente = db.Clientes.Find(id);
        if (cliente == null)
        {
            return HttpNotFound();
        }
        return View(cliente);
    }

    // POST: /Clientes/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Cliente cliente = db.Clientes.Find(id);
        db.Clientes.Remove(cliente);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

If you look closely, [Authorize] remains above the controller but in the Action Create I have set a new rule for I authorize with [Authorize(Roles="Administrador")] . In this way, Identity recognizes that all logged-in users can access / Clients / *** except / Customers / Create since a logged-in user with Administrator role is required.

Let's try this. I recommend that you delete the Permission table that you created since it is over since Identity has created one.

Create a user through the application in register after seeing in your DB how the user was created go to the table AspNetRoles and create a Rol manual ponle of Id 1 and Name Administrator, note that the name is = the one with [Authorize] in action Create .

After inserting the Rol go to the table AspNetUserRoles and in UserId you put the Id of the user that you created, it must be a cod hash and in RoleId you put 1 that is the Id of% % co that you created manually. In this way you specify a user with an Administrator role manually, remember that this is to see how the Authorize works for roles, in case you have the doubt Identity has methods to create roles and assign users to those roles but that would not explain it here.

Try entering rol with that user now and you will see how it leaves you. That is the approach you need to do what you want. I hope it helps you

    
answered by 04.12.2017 в 21:06