Files
Atomx/Atomx.Admin/Atomx.Admin/Middlewares/SecurityHeadersMiddleware.cs
2025-12-04 00:40:12 +08:00

57 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
namespace Atomx.Admin.Middlewares
{
/// <summary>
/// 安全中间件
/// </summary>
public class SecurityHeadersMiddleware
{
private readonly RequestDelegate _next;
private readonly IWebHostEnvironment _environment;
public SecurityHeadersMiddleware(RequestDelegate next, IWebHostEnvironment environment)
{
_next = next;
_environment = environment;
}
public async Task InvokeAsync(HttpContext context)
{
// 添加安全头
if (!context.Response.HasStarted)
{
var headers = context.Response.Headers;
// CSP策略
if (!_environment.IsDevelopment())
{
headers.Append("Content-Security-Policy",
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline' 'unsafe-eval'; " +
"style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data: https:; " +
"font-src 'self'; " +
"connect-src 'self' wss:; " +
"frame-ancestors 'none';");
}
// 其他安全头
headers.Append("X-Content-Type-Options", "nosniff");
headers.Append("X-Frame-Options", "DENY");
headers.Append("X-XSS-Protection", "1; mode=block");
headers.Append("Referrer-Policy", "strict-origin-when-cross-origin");
headers.Append("Permissions-Policy",
"camera=(), microphone=(), geolocation=(), interest-cohort=()");
// HSTS在生产环境中启用
if (!_environment.IsDevelopment())
{
headers.Append("Strict-Transport-Security",
"max-age=31536000; includeSubDomains; preload");
}
}
await _next(context);
}
}
}