Tuesday, February 26, 2019

SecurityException in the System.Security namespace in C#

This is a pretty good type of exception to use in a .NET Core 2.1 middleware breakout like this for throwing HttpStatusCode.Forbidden errors which should return a 403 instead of the more generic 500 you might associate with other exceptions. Pimp out your BubbleUpExceptions playa! It is probably good to also keep the specifics you log from coming back up from the API like so:

public override void OnException(ExceptionContext context)
{
   _logWriting.Log(_whereToLogTo,
         StringManipulations.FlattenException(context.Exception), _timekeeping);
   if (context.Exception is SecurityException)
   {
      context.Result = new JsonResult("{'Message': '" + context.Exception.Message + "'}");
      context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
   }
   else
   {
      context.Result = new JsonResult("{'Message': 'An error at the API occurred. The
            specific error message is being hidden from what the API exposes for security. If
            you have access to the logs you may see a better description free from
            obfuscation therein.'}");
      context.HttpContext.Response.StatusCode =
            (int)HttpStatusCode.InternalServerError;
   }
}

 
 

Addendum 4/30/2019: The use of JsonResult here is bad. See this instead.

No comments:

Post a Comment