如何在Spring中添加HTTP“ Feature-Policy”标头

时间:2018-07-19 08:34:10

标签: spring-boot spring-security content-security-policy

我需要添加HTTP“ Feature-Policy”响应标头,但我没有找到在春季在标头中实现此目的的任何方法,例如-

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        // ...
        .headers()
            .contentSecurityPolicy("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/");
    }

我可以看到规范草案here,但是在Spring中使用它的情况却很少。任何建议将不胜感激。

2 个答案:

答案 0 :(得分:1)

要创建自定义标题,您应该使用addHeaderWriter并添加StaticHeadersWriter

示例:

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        // ...
        .headers()
            .contentSecurityPolicy("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
            .and()
            .addHeaderWriter(new StaticHeadersWriter("Feature-Policy", "vibrate 'none'; usermedia 'none'"));
    }
}

答案 1 :(得分:0)

Spring Security在5.1中引入了对Feature-Policy的支持,因此可以将其配置为其他标头:

http
    .headers()
        .featurePolicy("geolocation 'none'");

对于5.2+版本,代码略有不同:

http
    .headers(headers ->
        headers.featurePolicy("geolocation 'none'")
    );

有关详细信息,请参见文档:


更新:@granty指出Feature-Policy标头已重命名为Permissions-Policy。即将推出的Spring Security 5.5.0-M2将支持它。这是它的样子:

http
    .headers(headers ->
        headers.permissionsPolicy(permissions ->
            permissions.policy("geolocation=(self)")
        )
    );

另请参阅相关的提取请求:#9265