简体   繁体   中英

.net core security headers middleware not adding headers to external http requests

I'm using security headers middleware in a web app to add security headers to all outgoing http requests. Security headers seem to get added to all network requests to internal resources - that is resources that make up the web app such as the javascript scripts and the images used in the web app and the css and html files. However the security headers do not get added to any external http requests such as to an API that I made that the web app uses to get json data. How do I make it just add security headers to everything, rather than just to the web apps own resources?

Below is some of the relevant code that adds security headers middleware

startup.cs

private ILogger<SecurityHeadersBuilder> _logger;
private readonly SecurityHeadersPolicy _policy = new SecurityHeadersPolicy();

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ISecurityHeadersBuilder securityHeadersBuilder)
{...
    app.UseSecurityHeadersMiddleware(
        securityHeadersBuilder.AddDefaultSecurePolicy()
    );

securityHeadersBuilder.cs

public SecurityHeadersBuilder AddDefaultSecurePolicy()
{
    AddFrameOptionsDeny();
    AddXssProtectionBlock();
    AddContentTypeOptionsNoSniff();
    AddNoCache();
    AddStrictTransportSecurityMaxAgeIncludeSubDomains();
    AddContentSecurityPolicyAllContentFromSelfAndGoogle();
    RemoveServerHeader();
    return this;
}

public SecurityHeadersBuilder AddFrameOptionsDeny()
{
    _policy.SetHeaders[FrameOptionsConstants.Header] = FrameOptionsConstants.Deny;
    _logger.LogInformation(string.Format("setting {0} http header value to {1}", FrameOptionsConstants.Header, FrameOptionsConstants.Deny));
    return this;
}

There are two type of headers: request headers and _response headers.

The server sets response headers to instruct the browser how to handle a response (block iframing for example). Therefore it would not make sense to do a request with (for example) the header X-Frame-Options : Deny . Because the client application could alter the value and ignore the security restriction. The server will not handle the value of the header anyway, the user-agent of the browser will use this response header.

If you do a call to an (external) API you should manually add request headers to an HttpClient and make the call. The API in turn can return the (security) response headers.

All the headers that you have in the example code are response headers and should not be set as request headers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM