I'm developing a web application, using Asp.Net MVC 5 com Identity
and I'm using Roles
to perform the authorization.
I am trying to do that depending on the Role
that the user has, it is directed to a different "Home" page.
Example:
- Administrators = > Home of the 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 I have access denied by Roles
, I sub-wrote the HandleUnauthorizedRequest
method:
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 attempting to validate using the condition: if(UserManager.IsInRole(User.Identity.GetUserId(), "admin"))
the error was generated:
CodeofHomeController
:
publicclassHomeController:Controller{[PermissoesFiltro]publicActionResultIndex(){returnView();}[PermissoesFiltro(Roles="Comercial")]
public ActionResult Index_Comercial()
{
return View();
}
[PermissoesFiltro(Roles = "Master")]
public ActionResult Index_Master()
{
return View();
}
Identity Tables: