首页 > 解决方案 > Spring:如何保护登录页面免受 csrf 的影响(不进行重大更改)?

问题描述

我有一个使用 Spring 的 Java 项目。

我需要保护登录页面免受 CSRF 攻击。

目前,我的 Spring xml 配置文件包含

<http>
    ...
    <csrf disabled="true"/>
</http>

由于项目的规模,我现在无法更改所有页面并保护它们免受 CSRF 攻击,但我想至少保护这个,我认为这是最重要的页面之一。特别是,我无法保护使用 GET 请求的 /logout 端点(这将是一项重大更改)。

如何在没有注销请求的情况下保护登录页面?

我试图这样做:

<bean id="csrfMatcher" class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
    <constructor-arg name="pattern" value="/j_spring_security_check"/>
    <constructor-arg name="httpMethod" value="POST"/>
</bean>
<csrf request-matcher-ref="csrfMatcher" />

并在现有的登录表单中添加这段代码:

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />

但是,注销请求也会受到此更改的影响,它希望避免这种情况。

谢谢

标签: javaspringspring-securitycsrf

解决方案


假设您只使用这 4 个 http 方法(get、post、put、delete),这个正则表达式将忽略除登录之外的所有路径

http.csrf(csrf -> csrf.ignoringRequestMatchers(new RegexRequestMatcher("^(?!/login).*", "get"),
                    new RegexRequestMatcher("^(?!/login).*", "post"),
                    new RegexRequestMatcher("^(?!/login).*", "delete"),
                    new RegexRequestMatcher("^(?!/login).*", "put")
                    ).disable());

推荐阅读