Skip to content

Instantly share code, notes, and snippets.

@marcominerva
Last active March 22, 2018 13:25
Show Gist options
  • Save marcominerva/dc51dbfe7fc71dedc452e3aaae61f50c to your computer and use it in GitHub Desktop.
Save marcominerva/dc51dbfe7fc71dedc452e3aaae61f50c to your computer and use it in GitHub Desktop.
Handle forbidden authorization with ASP.NET MVC
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ForbiddenAuthorizeAttribute : AuthorizeAttribute
{   
public string ForbiddenViewName { get; set; } = "Forbidden";
   
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
// Access forbidden, display 403 page (instead of the default login page, because the user is actually already
// authenticated but he hasn't access to this page).  
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;  
var forbiddenView = new ViewResult { ViewName = ForbiddenViewName };  
filterContext.Result = forbiddenView;   
else
{
base.HandleUnauthorizedRequest(filterContext);      
}   
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment