4
I am developing a web application, using Asp.Net MVC 5 com Identity and I’m using Roles to carry out the authorisation.
I’m trying to do that depending on the Role that the user has, it is directed to a different "Home" page.
Example:
- Administrators => Home Administration;
- Sellers => Home of the Commercial.
And so it goes. But I’m having a hard time finding a solution.
To redirect the user when denied access by Roles, I sub-wrote the method HandleUnauthorizedRequest:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// The user is not authenticated
base.HandleUnauthorizedRequest(filterContext);
}
else if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
{
// The user is not in any of the listed roles =>
// show the unauthorized view
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Shared/Page_403.cshtml"
};
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
Now, to perform this redirect, after logging in? how would you do?
Controller Code Account:
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
When trying to validate using the condition: if(UserManager.IsInRole(User.Identity.GetUserId(), "admin"))
error was generated:
Code of HomeController:
public class HomeController : Controller
{
[PermissoesFiltro]
public ActionResult Index()
{
return View();
}
[PermissoesFiltro(Roles = "Comercial")]
public ActionResult Index_Comercial()
{
return View();
}
[PermissoesFiltro(Roles = "Master")]
public ActionResult Index_Master()
{
return View();
}
Tables of Identity:


You have not posted the code where you validate the login, you are using
FormsAuth.SignIn? But it would be enough to execute oneRedirectToAction. Might explain your problem better?– Ricardo Pontual
@Ricardopunctual I did a review and posted the controller code, I am using the standard that comes with Identity, which added login redirects to the default home. My doubt, it’s like checking the
Roleuser and direct to different pages?– Thomas Erich Pimentel