I have created a customized role base authorization attribute.My idea is that when a user with role name \"employee\" Log In should not be allowed to access the \"admin\" p
Your redirection code is always going to redirect the user to the Employee Index Action, even when the action your are redirecting to is authenticated for the employee. You will need to provide another set of rules in your authorization and change your OnAuthorize method.
Such as
public class MyRoleAuthorization : AuthorizeAttribute
{
///
/// the allowed types
///
readonly string[] allowedTypes;
///
/// Default constructor with the allowed user types
///
///
public MyRoleAuthorization(params string[] allowedTypes)
{
this.allowedTypes = allowedTypes;
}
///
/// Gets the allowed types
///
public string[] AllowedTypes
{
get { return this.allowedTypes; }
}
///
/// Gets the authorize user
///
/// the context
///
private string AuthorizeUser(AuthorizationContext filterContext)
{
if (filterContext.RequestContext.HttpContext != null)
{
var context = filterContext.RequestContext.HttpContext;
string roleName = Convert.ToString(context.Session["RoleName"]);
switch (roleName)
{
case "Admin":
case "Employee":
case "Customer":
return roleName;
default:
throw new ArgumentException("filterContext");
}
}
throw new ArgumentException("filterContext");
}
///
/// The authorization override
///
///
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
throw new ArgumentException("filterContext");
string authUser = AuthorizeUser(filterContext);
if (!this.AllowedTypes.Any(x => x.Equals(authUser, StringComparison.CurrentCultureIgnoreCase)))
{
filterContext.Result = new HttpUnauthorizedResult();
return;
}
}
}
This can then be decorated as
public class EmployeeController : Controller
{
[MyRoleAuthorization("Employee")]
public ActionResult Index()
{
return View();
}
}
Now your login code should be modified to send the user to the correct controller.