Search code examples
asp.net-corecontent-security-policyendpointasp.net-core-middleware

Content Security Policy Endpoint cspreport not found POST https://localhost:44331/cspreport returns 404 Asp.net Core


I want to add Content Security Policy reporting and for that I've followed this along.

My CspReportRequest class is:

public class CspReportRequest
{
    [JsonPropertyName("csp-report")]
    public CspReport CspReport { get; set; }
}

public class CspReport
{
    [JsonPropertyName("document-uri")]
    public string DocumentUri { get; set; }

    [JsonPropertyName("referrer")]
    public string Referrer { get; set; }

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

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

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

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

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

In my HomeController I have:

[HttpPost]
    [Consumes("application/cspreport")]
    public IActionResult CSPReport([FromBody] CspReportRequest cspReportRequest)
    {
        Console.WriteLine(cspReportRequest);
        return Ok();
    }

And to avoid 415 errors I've also implemented

services.AddControllersWithViews().AddMvcOptions(options =>
        {
            var jsonInputFormatter = options.InputFormatters
                .OfType<SystemTextJsonInputFormatter>()
                .Single();

            jsonInputFormatter.SupportedMediaTypes.Add("application/csp-report");
        });

My context.Response.Headers, simplified for brevity:

context.Response.Headers.Add(
"Content-Security-Policy-Report-Only",
"default-src 'self' ;" +
"script-src-elem 'self' ;" +
"script-src 'self' ;" +
"style-src-elem 'self' ;" +
"img-src 'self' " +
"font-src 'self' " +
"media-src 'self'  ;" +
"frame-src 'self' ;" +
"connect-src 'self' " +
"object-src 'none' ;" +
"base-uri 'self' ;" +
"report-uri /cspreport ;"
);

My problem is that I see the CSP Request using the developers tools but with a 404 error. If I try with Postman I get the same error as well.

enter image description here

What am I doing wrong?


Solution

  • Your URL in not correct,if you did not change the default route settings,the correct URL should be https://localhost:44331/Home/Cspreport

    you could read the document related :https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-5.0#route-template-reference