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" page through URL. But when I implement the [MyRoleAuthorization]
in Employee controller and Log In the error says "This webpage has a redirect loop".
This is code for [MyRoleAuthorization]
public class MyRoleAuthorization : AuthorizeAttribute
{
string isAuthorized;
private string AuthorizeUser(AuthorizationContext filterContext)
{
if (filterContext.RequestContext.HttpContext != null)
{
var context = filterContext.RequestContext.HttpContext;
if (Convert.ToString(context.Session["RoleName"]) == "Admin")
{
isAuthorized = "Admin";
}
else if (Convert.ToString(context.Session["RoleName"]) == "Employee")
{
isAuthorized = "Employee";
}
else if (Convert.ToString((context.Session["RoleName"])) == "Customer")
{
isAuthorized = "Customer";
}
else
{
throw new ArgumentException("filterContext");
}
}
return isAuthorized;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
throw new ArgumentException("filterContext");
if (AuthorizeUser(filterContext) == "Admin")
{
filterContext.Result = new RedirectToRouteResult
(new RouteValueDictionary(new { controller = "Admin" }));
}
else if (AuthorizeUser(filterContext) == "Employee")
{
filterContext.Result = new RedirectToRouteResult
(new RouteValueDictionary(new { controller = "Employee" }));
}
else if (AuthorizeUser(filterContext) == "Customer")
{
filterContext.Result = new RedirectToRouteResult
(new RouteValueDictionary(new { controller = "Customer" }));
}
}
}
}
My Employee controller looks like this
[MyRoleAuthorization]
public ActionResult Index()
{
var employee = db.Employee.Include(e => e.User);
return View(employee.ToList());
}
Can you please help me.
Your biggest problem is when you go to the employee controller as an employee, you're redirected to the employee controller, where your attribute redirects you to the employee controller and so on. Try to avoid redirecting within the attribute as it makes your code brittle & when you come back in a years time, you won't remember why your routes don't work as you intend
Try this:
It seems that when authorized, you redirect to the Customer controller, for example. This controller likely has your attribute on it, and so it authorizes the user, who is seen as a customer, and redirects to the Customer controller... Which has your attribute on it, and so it authorizes the user...
Infinite loop.
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
}
This can then be decorated as
Now your login code should be modified to send the user to the correct controller.