UPDATE (Jun 2015): @ daniel-lidström correctly pointed out that you should not use Response.Redirect in an ASP.NET MVC application. For more information on why, please see this link: Response.Redirect and ASP.NET MVC - do not mix .
UPDATE (September 2014): I am not sure when HandleUnauthorizedRequest was added to AuthorizeAttribute, but in any case I managed to refine the AuthorizeRedirect code into something smaller and simpler.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class AuthorizeRedirect : AuthorizeAttribute { public string RedirectUrl = "~/Error/Unauthorized"; protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); if (filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.Result = new RedirectResult(RedirectUrl); } } }
Original answer Below (still fully functional)
I left this answer here, because it still gives you an idea of how the authorization pipeline works.
For those who are still landing here, I edited Ben Sheyrman's answer to automatically redirect to an unauthorized page when the user logged in, but did not log in. You can change the redirect path using the name parameter RedirectUrl.
EDIT: I made the solution thread safe thanks to the advice of Tarynn and MSDN
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class AuthorizeRedirect : AuthorizeAttribute { private const string IS_AUTHORIZED = "isAuthorized"; public string RedirectUrl = "~/error/unauthorized"; protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { bool isAuthorized = base.AuthorizeCore(httpContext); httpContext.Items.Add(IS_AUTHORIZED, isAuthorized); return isAuthorized; } public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); var isAuthorized = filterContext.HttpContext.Items[IS_AUTHORIZED] != null ? Convert.ToBoolean(filterContext.HttpContext.Items[IS_AUTHORIZED]) : false; if (!isAuthorized && filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.RequestContext.HttpContext.Response.Redirect(RedirectUrl); } } }
Ben Cull Mar 08 '11 at 23:15 2011-03-08 23:15
source share