Kes*_*hab 3 c# asp.net security asp.net-web-api asp.net-core
我需要向新的 ASP.NET Core 3.1 Web API 添加一些安全标头。在 MVC 和 webform 中,我曾经在 web.config 文件中使用以下代码:
<httpProtocol>
<customHeaders>
<add name="Strict-Transport-Security" value="max-age=31536000"/>
<add name="X-Content-Type-Options" value="nosniff"/>
<add name="X-Xss-Protection" value="1; mode=block"/>
<add name="X-Frame-Options" value="SAMEORIGIN"/>
<add name="Content-Security-Policy" value="default-src https:; img-src * 'self' data: https:; style-src 'self' 'unsafe-inline' www.google.com platform.twitter.com cdn.syndication.twimg.com fonts.googleapis.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' www.google.com cse.google.com cdn.syndication.twimg.com platform.twitter.com platform.instagram.com www.instagram.com cdn1.developermedia.com cdn2.developermedia.com apis.google.com www.googletagservices.com adservice.google.com securepubads.g.doubleclick.net ajax.aspnetcdn.com ssl.google-analytics.com az416426.vo.msecnd.net/;"/>
<add name="Referrer-Policy" value="no-referrer-when-downgrade"/>
<add name="Feature-Policy" value="geolocation 'none';midi 'none';notifications 'none';push 'none';sync-xhr 'none';microphone 'none';camera 'none';magnetometer 'none';gyroscope 'none';speaker 'self';vibrate 'none';fullscreen 'self';payment 'none';"/>
<remove name="X-Powered-By" />
<remove name="X-AspNet-Version" />
<remove name="Server" />
</customHeaders>
</httpProtocol>
Run Code Online (Sandbox Code Playgroud)
我知道我们也可以在 .NET Core 中拥有一个 web.config 文件,但我想通过在启动类中添加自定义代码来实现这一点。我发现很少有文章使用一些 NUGET 包,但如果有人能给我一个清晰的图片来在 .Net Core 中添加安全标头,那就太棒了。提前致谢。
Ank*_*ain 14
CustomResponseHeaderMiddleware在代码中创建一个像这样的中间件类:
public class CustomResponseHeaderMiddleware
{
private readonly RequestDelegate _next;
public CustomResponseHeaderMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
//To add Headers AFTER everything you need to do this
context.Response.OnStarting(state =>
{
var httpContext = (HttpContext)state;
httpContext.Response.Headers.Add("Strict-Transport-Security", "max-age=31536000");
httpContext.Response.Headers.Add("X-Content-Type-Options", "nosniff");
httpContext.Response.Headers.Add("X-Xss-Protection", "1; mode=block");
httpContext.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
//... and so on
return Task.CompletedTask;
}, context);
await _next(context);
}
}
Run Code Online (Sandbox Code Playgroud)
startup.cs并在文件中注册这个中间件
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ....
app.UseMiddleware(typeof(CustomResponseHeaderMiddleware));
app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14083 次 |
| 最近记录: |