java - 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}" />
但是,注销请求也会受到此更改的影响,它希望避免这种情况。
谢谢
解决方案
假设您只使用这 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());
推荐阅读
- java - 在按钮单击android上以编程方式将项目添加到操作应用程序栏菜单
- javascript - 如何使用弹出窗口调试 chrome 扩展?
- angular - mat-autocomplete 使用 ngx-perfect-scrollbar 错误
- javascript - 如何向 JSFiddle 添加外部图像?
- reactjs - 为什么 Material-UI Select 不显示任何选项?
- javascript - 如何在nodejs中每天过去时获取日期?
- javascript - 使用 JavaScript 为行和列选择第 n 个子元素后,未创建输入元素
- td-engine - 在 TDengine 数据库中批量插入期间更新不起作用
- hadoop - HIVE - 我如何转换时间戳和总和值
- javascript - 如何在 React 状态下动态更新对象键