簡體   English   中英

使用 Spring Boot 應用程序啟用 HTTP 嚴格傳輸安全 (HSTS)

[英]Enable HTTP Strict Transport Security (HSTS) with spring boot application

我已按照文章https://docs.spring.io/spring-security/site/docs/4.0.2.RELEASE/reference/html/headers.html#headers-hsts在我的 Spring Boot 應用程序上啟用 HSTS 標頭。 盡管進行了必要的更改,但Strict-Transport-Security標頭並未出現響應。

pom.xml(依賴項)

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
    </dependency>
</dependencies>

WebSecurityConfig.java

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .headers()
            .httpStrictTransportSecurity()
                .includeSubDomains(true)
                .maxAgeInSeconds(31536000);
    }
}

標題列表:

cache-control →no-cache, no-store, max-age=0, must-revalidate
content-language →en-GB
content-type →text/html;charset=UTF-8
date →Thu, 24 May 2018 14:10:29 GMT
expires →0
pragma →no-cache
transfer-encoding →chunked
x-application-context →application:9000
x-content-type-options →nosniff
x-frame-options →SAMEORIGIN
x-xss-protection →1; mode=block

我錯過了什么嗎?

根據 RFC6797,HSTS 標頭僅注入到 HTTPS 響應中。

來源: https ://docs.spring.io/spring-security/site/docs/4.0.2.RELEASE/reference/htmlsingle/#headers-hsts

它只會在通過 HTTPS 的第一個請求之后出現。

如其他答案中所述, HstsConfig中使用的默認RequestMatcher正在檢查請求是否為 HTTPS。 如果它不適合您,您可以設置另一個匹配器,因為 TLS 不會被 Spring Boot 終止。

下面的代碼確保在所有響應中都設置了Strict-Transport-Security標頭:

    http.headers()
          .httpStrictTransportSecurity()
          .requestMatcher(AnyRequestMatcher.INSTANCE)
          ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM