Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Authorize in MVC 4.0 Razor

Basically I want to add 2 view in my project/website. One for Admin and another for User. I already add [Authorize] tag in my target controller and it works.

After use [Authorize] tag when I try to insert something that time it redirect to registration page and any of the registration member can input data. But how can I specific an admin who can input data in table ??

I watch several tutorial and video but there working approach is not clear for me. In plural site video they use Seed data and write a method in there. But I input data in database. So, how can I work with this video tutorial ?? Because I don't have any seed data.

like image 433
mgsdew Avatar asked May 10 '14 14:05

mgsdew


1 Answers

You can restrict your user on view by just not showing html to him with simple if statement:

@if (User.IsInRole("Admin"))
{
   //here blocks that you want to show to users with Admin role   
}

Also you can decorate some specific actions with [Authorize] attribute like that:

[Authorize(Roles = "Admin")]
public ActionResult SaveTopSecret()
{

}

User.IsInRole("Admin") also available in the controller, so you can decide which view you want to show to which user:

public ActionResult Index()
{
    if(User.IsInRole("Admin"))
    {
        return View("Admin");
    }
    return View("User");
}
like image 77
Oleksii Aza Avatar answered Sep 27 '22 23:09

Oleksii Aza