tyr*_*yro 6 spring-security spring-boot
我正在将应用程序从 Spring Boot 1.5 迁移到 2.0.5。我有一个security.enable-csrf=true在 1.5 版本中设置的属性,但在 2.0 版本的 Spring Boot 中不可用。
我阅读了文档,据说在 Spring Boot 2.0 中:
在 Java 配置中默认启用 CSRF 保护。
所以默认情况下它是启用的,但也创建了一个类,它扩展了WebSecurityConfigurerAdapter这意味着 Spring Boot 默认安全配置已被关闭。这是否也意味着security.enable-csrf现在被禁用了?
如果是,我该如何启用它,就像我在 1.5 版本的应用程序中使用它一样。
我没有得到任何文件明确确认如何security.enable-csrf在 Spring Boot 2.0 中处理属性以及在声明WebSecurityConfigurerAdapter.
有人知道吗?此外,我错过阅读有关此内容的任何文档链接都会有很大帮助。
为了与已在您的应用程序中设置的属性向后兼容security.enable-csrf=true,您可以使用以下代码:
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Value("${security.enable-csrf}")
private boolean csrfEnabled;
@Override
protected void configure(HttpSecurity http) throws Exception {
if (!csrfEnabled) {
http.csrf().disable();
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如你可能猜到的魔法来自
http.csrf().disable();于上面的代码,你可以通过你在 application.properties 文件中设置的属性来控制启用/禁用它。
更多信息:
更多细节你也可以参考spring文档:
WebSecurityConfigurerAdapter是一个抽象类,当你创建一个扩展的类时WebSecurityConfigurerAdapter,你将重写void configure(HttpSecurity http)方法。
你可以在这个方法中禁用csrf,就像这样;
http.csrf().disable();
Run Code Online (Sandbox Code Playgroud)
您可以在方法顶部csrf()(在HttpSecurity课堂上)阅读此注释。
添加 CSRF 支持。
WebSecurityConfigurerAdapter当使用 的默认构造函数时,默认情况下会激活此功能 。你可以禁用它......”
这个注释说,当你扩展这个类时,WebSecurityConfigurerAdapterworks 和 csrf 的默认构造函数被激活。
| 归档时间: |
|
| 查看次数: |
4747 次 |
| 最近记录: |