使用Spring Boot应用程序启用HTTP Strict Transport Security(HSTS)

kk.*_*kk. 3 java spring spring-security hsts spring-boot

我已关注文章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>
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

标头列表:

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
Run Code Online (Sandbox Code Playgroud)

我有什么想念的吗?

pro*_*e-e 6

正如其他答案中提到的,默认RequestMatcher使用的HstsConfig是检查请求是否是 HTTPS。如果它不适合您,您可以设置另一个匹配器,因为 TLS 不会被 Spring Boot 终止。

下面的代码确保Strict-Transport-Security在所有响应中设置标头:

    http.headers()
          .httpStrictTransportSecurity()
          .requestMatcher(AnyRequestMatcher.INSTANCE)
          ...
Run Code Online (Sandbox Code Playgroud)


Pri*_*1me 5

它只会在第一次通过 HTTPS 请求后出现。