Подробности настройки:< /p>
Промежуточное программное обеспечение заголовка CSP:
Я добавил промежуточное программное обеспечение для установки заголовка CSP, которое включает директиву report-uri:
Код: Выделить всё
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Use(async (ctx, next) =>
{
ctx.Response.Headers.Add("Content-Security-Policy", "default-src 'self'; script-src 'self'; report-uri /csp-report;");
await next();
});
// Other middleware...
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllers();
});
}
Я создал контроллер для обработки запросов POST в конечной точке /csp-report:
Контроллер для обработки отчетов CSP:
Я создал контроллер для обработки запросов POST в конечной точке /csp-report:
п>
Код: Выделить всё
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using APP.APP1.Entities.Definitions.CspReporting;
using Microsoft.AspNetCore.Authorization;
namespace APP.APP1.UI.Controllers
{
[Route("csp-report")]
[ApiController]
public class CspReportController : ControllerBase
{
private readonly ILogger _logger;
public CspReportController(ILogger logger)
{
_logger = logger;
}
[HttpPost]
[AllowAnonymous]
public IActionResult CspReport([FromBody] CspReportRequest request)
{
if (request == null || request.CspReport == null)
{
return BadRequest("Invalid CSP report");
}
// Log the CSP report
_logger.LogWarning($"CSP Violation: Document URI: {request.CspReport.DocumentUri}, Blocked URI: {request.CspReport.BlockedUri}");
return Ok();
}
}
}
Код: Выделить всё
using Newtonsoft.Json;
namespace APP.APP1.Entities.Definitions.CspReporting
{
public class CspReportRequest
{
[JsonProperty("cspReport")]
public CspReport CspReport { get; set; }
}
public class CspReport
{
[JsonProperty("document-uri")]
public string DocumentUri { get; set; }
[JsonProperty("referrer")]
public string Referrer { get; set; }
[JsonProperty("blocked-uri")]
public string BlockedUri { get; set; }
[JsonProperty("violated-directive")]
public string ViolatedDirective { get; set; }
[JsonProperty("effective-directive")]
public string EffectiveDirective { get; set; }
[JsonProperty("original-policy")]
public string OriginalPolicy { get; set; }
[JsonProperty("disposition")]
public string Disposition { get; set; }
[JsonProperty("status-code")]
public int StatusCode { get; set; }
[JsonProperty("script-sample")]
public string ScriptSample { get; set; }
[JsonProperty("line-number")]
public int LineNumber { get; set; }
[JsonProperty("column-number")]
public int ColumnNumber { get; set; }
[JsonProperty("source-file")]
public string SourceFile { get; set; }
}
}
п>
Код: Выделить всё
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using System.Linq;
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.Configure(options =>
{
var jsonInputFormatter = options.InputFormatters.OfType().First();
jsonInputFormatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/csp-report"));
});
// Other service registrations...
}
Код: Выделить всё
fetch('/csp-report', {
method: 'POST',
headers: {
'Content-Type': 'application/csp-report'
},
body: JSON.stringify({
cspReport: {
"document-uri": "http://example.com/test",
"referrer": "",
"violated-directive": "script-src-elem",
"effective-directive": "script-src-elem",
"original-policy": "default-src 'none'; script-src 'self';",
"disposition": "report",
"blocked-uri": "http://malicious.com/script.js",
"line-number": 1,
"column-number": 1,
"source-file": "http://example.com/test"
}
})
}).then(response => {
if (response.ok) {
console.log("CSP report sent successfully.");
} else {
console.error("Failed to send CSP report.");
}
});
Несмотря на все настройки, объект CspReportRequest в действии контроллера остается нулевым, а свойства объекта CspReport заполняются неправильно.
Вот полезные данные, отправленные в запросе:
Код: Выделить всё
{
"cspReport": {
"document-uri": "http://example.com/test",
"referrer": "",
"violated-directive": "script-src-elem",
"effective-directive": "script-src-elem",
"original-policy": "default-src 'none'; script-src 'self';",
"disposition": "report",
"blocked-uri": "http://malicious.com/script.js",
"line-number": 1,
"column-number": 1,
"source-file": "http://example.com/test"
}
}
Код: Выделить всё
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"traceId": "|553d9216-43a24081a09550b4."
}
- Убедился, что структура JSON соответствует свойствам модели.
Добавлено Атрибуты JsonProperty соответствуют именам свойств JSON.
Настроен SystemTextJsonInputFormatter для поддержки типа носителя application/csp-report. - Проверено, что полезные данные структурированы правильно.
Дополнительный контекст:
- ASP.NET Core 5.0
< li>Использование System.Text.Json для сериализации/десериализации JSON.
Подробнее здесь: https://stackoverflow.com/questions/785 ... p-net-core
Мобильная версия