如何仅在localhost中禁用spring security中的csrf?

时间:2018-02-11 13:30:15

标签: spring-boot spring-security csrf

我有一个工作的spring boot应用程序,其中启用了csrf,但现在我只想为localhost禁用它。来自其他域的任何请求都必须通过csrf安全性,但对于localhost,我想禁用它。我怎么能实现呢?

我知道如何通过更改

来禁用它
@Configuration
@EnableWebMvcSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf.disable();
    }
}

上面的代码禁用了csrf,但我想为唯一的localhost禁用csrf。

你能帮帮我吗?

编辑:我知道如何通过两个配置文件来完成它。谢谢@daren的详细解答。

2 个答案:

答案 0 :(得分:1)

您可以使用Spring Profiles来实现您的目标。

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

最简单的你可以有两种配置

@Configuration
@EnableWebMvcSecurity
@Profile("!deployed") //Not(!) deployed profile
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf.disable();
    }
}

在已部署的区域中激活deployed个人资料。

@Configuration
@EnableWebMvcSecurity
@Profile("deployed")
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf.enable();
    }
}

根据您正在执行的安全配置,您可以执行相反的操作并默认激活本地配置文件,这将禁用此功能。

答案 1 :(得分:0)

您可以使用CsrfConfigurer#requireCsrfProtectionMatcher方法并使用RequestMatcher来检查请求的本地地址还是远程地址,例如

private RequestMatcher csrfProtectionMatcher() {
    final Set<String> allowedMethods = ImmutableSet.of("GET", "HEAD", "TRACE", "OPTIONS");
    return request -> !allowedMethods.contains(request.getMethod()) && !(request.getLocalAddr().equals(request.getRemoteAddr()));
}
相关问题