Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow Content Security Policy logging. #147

Open
malylemire1 opened this issue Jul 14, 2022 · 0 comments
Open

Allow Content Security Policy logging. #147

malylemire1 opened this issue Jul 14, 2022 · 0 comments

Comments

@malylemire1
Copy link

malylemire1 commented Jul 14, 2022

It would be nice to have nicely displayed page for content security policy errors.

For now I use something like this

[HttpPost("~/cspreport")]
       public IActionResult CspReport([FromBody] CspReportRequest request)
       {
           this.LogParams((nameof(CspReportRequest), request));

           HttpContext.RaiseError(new ContentSecurityPolicyException(request));

           return Ok();
       }
   }

   [Serializable]
   public class ContentSecurityPolicyException : Exception
   {
       /// <summary>
       /// Default constructor.
       /// </summary>
       public ContentSecurityPolicyException(CspReportRequest request)
           : base($"Content Security Policy: {request.CspReport.DocumentUri} ({request.CspReport.ViolatedDirective})")
       {
       }
   }

   public class CspReportRequest
   {
       [JsonProperty(PropertyName = "csp-report")]
       public CspReport CspReport { get; set; }
   }
   public class CspReport
   {
       [JsonProperty(PropertyName = "document-uri")]
       public string DocumentUri { get; set; }

       [JsonProperty(PropertyName = "referrer")]
       public string Referrer { get; set; }

       [JsonProperty(PropertyName = "violated-directive")]
       public string ViolatedDirective { get; set; }

       [JsonProperty(PropertyName = "effective-directive")]
       public string EffectiveDirective { get; set; }

       [JsonProperty(PropertyName = "original-policy")]
       public string OriginalPolicy { get; set; }

       [JsonProperty(PropertyName = "blocked-uri")]
       public string BlockedUri { get; set; }

       [JsonProperty(PropertyName = "status-code")]
       public int StatusCode { get; set; }
   }

services.Configure<MvcOptions>(options =>
           {
               var formatter = options.InputFormatters.OfType<NewtonsoftJsonInputFormatter>().LastOrDefault();
               formatter.SupportedMediaTypes
                   .Add(MediaTypeHeaderValue.Parse("application/csp-report"));
           });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant