My questions:
When a user doesn't have Manager role and Admin role, I have to redirect to an error page/some popup message. But when the user is not authorized, the Windows security password prompt continuously keeps showing. When I enter the user name and password again, it's showing Windows security password.
Every action method I have to check and I need to show the message or error page.
How do I solve this issue?
Controller code:
[AuthorizeUser("Manager","Admin")]
public ActionResult Contact()
{
return View();
}
C# code:
public AuthorizeUserAttribute(params int[] roles)
{
allowedroles = roles;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool authorize = false;
var getList = _objService.GetUserRoleDetail(CommonStaticHelper.getLoggedUser());
foreach (var role in allowedroles)
{
if (getList.Exists(m => m.RoleId == role))
{
return authorize = true; /* return true if Entity has current user(active) with specific role */
}
}
return authorize;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new HttpUnauthorizedResult();
}
Try this :
// Create an action :
public ActionResult Unauthorized()
{
return View();
}
// now write below code for authorization:
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
// redirect to the Unauthenticated page
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Error", action = "Unauthorized" })
);
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
// The user is not authenticated
return false;
}
else
{
var getList = _objService.GetUserRoleDetail(CommonStaticHelper.getLoggedUser());
foreach (var role in allowedroles)
{
if (getList.Exists(m => m.RoleId == role))
{
// return true if Entity has current
// user(active) with specific role
return authorize = true;
}
}
return authorize = false;
}
}