如何在Spring Security中仅禁用localhost的CSRF?

4

我有一个正在工作的Spring Boot应用程序,其中启用了csrf,但现在我想仅针对本地主机禁用它。任何来自其他域的请求都必须绕过csrf安全性,但是对于本地主机,我想禁用它。怎样才能实现呢?

我知道如何通过更改以下内容来禁用它:

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

上面的代码禁用了csrf,但我只想禁用localhost的csrf。
你能帮我吗?
编辑:我知道如何通过两个配置文件来实现。感谢@daren提供的详细答案。

禁用本地主机是什么意思? - Ali.Wassouf
2个回答

3
你可以使用 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()));
}

使用如下方式: httpSecurity.requestMatcher(csrfProtectionMatcher()).csrf() - undefined

3
您可以使用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();
    }
}

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

我不知道其他的方法,但是我们可以使用配置文件来处理这种情况。你也可以使用其他更复杂的标志,但最终都会基于某种类型的配置文件。 - Darren Forsythe
1
@VishalPatel 另一个解决方案是使用多个Spring Security配置。第一个仅针对localhost,使用自定义请求匹配器。 - dur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接