Search code examples
asp.net-mvcasp.net-mvc-4asp.net-identitywifclaims-based-identity

Failing claim gives 500 instead of 403


We use the Claims principal attribute from our MVC controllers. Problem is if a unauthorized user access the site he gets a 500 instead of a 403 which is not very user friendly (If he gets a 403 he knows he needs to call help desk to order correct user privilege).

What is the correct way of making sure the Security exception results in a 403? I've seen alot of creative ways when googling, but not a solid solution.

[ClaimsPrincipalPermission(SecurityAction.Demand, Resource = "Foo", Operation = "Post")]

Solution

  • Using your own Claims attribute like trailmax suggested works, but only for code in the Web layer, but business logic below can still use the claims attribute. A better solution to my problem is to use a custom HandleErrorAttribute

    public class HandleClaimsErrorAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);
            if (filterContext.Exception is SecurityException)            
                filterContext.HttpContext.Response.StatusCode = 403;            
    
        }
    }
    

    http://andersmalmgren.com/2015/01/23/mvc-custom-errors-http-status-codes-and-securityexception/