In my ASP.NET MVC app, I have most controllers decorated with
[Authorize(Roles=\"SomeGroup\")]
When a user is not authorized to access som
Ben Cull's method works well, but remember there are two AuthorizeAttribute classes - one in System.Web.HTTP (used by Web API), and the other in System.Web.Mvc. Ben's method uses the System.Web.Mvc class. For clarity, I suggest using the fully qualified path.
If you're using Web API alongside MVC, you will need to implement two filters:
public class AuthorizeRedirectMVCAttribute : System.Web.Mvc.AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
if (filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectResult("~/Account/AccessDenied");
}
}
}
public class AuthorizeRedirectAPIAttribute : System.Web.Http.AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
base.HandleUnauthorizedRequest(actionContext);
if (actionContext.RequestContext.Principal.Identity.IsAuthenticated)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
}
}
}
Note that asp.net will let you decorate your MVC controller with an API filter - it just won't work the way you expect, so keep your attribute names explicit.