试图在最新的 Spring Boot 上实现 CSRF 保护。 网上的例子都是基于用户登录和认证的,我不需要。
我的站点没有任何需要身份验证的部分。 我愿意
1) Rest requests come from within site. No direct request from outside with wget to be allowed.
2) All pages (routes) must be requested from the index page (/)
在 pom.xml
中包含安全依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
-- 在application.properties
中定义用户(尽管我不需要)
-- 应用程序创建 _csrf.token
。
-- 创建的类扩展 WebSecurityConfigurerAdapter
并覆盖“configure”方法。
在“配置”中尝试了所有建议的过滤器。它没有用,最后留空了。
问题是wget可以直接获取api页面。 如何预防?
最佳答案
我已经快速整理了此配置的 POC:
@Configuration
@EnableWebSecurity
@SpringBootApplication
public class StackoverflowQ40929943Application extends WebSecurityConfigurerAdapter{
public static void main(String[] args) {
SpringApplication.run(StackoverflowQ40929943Application.class, args);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll();
}
}
它的要点是 Spring Boot + Security 将自动保护所有端点。在这里,我们明确允许对所有端点的请求。但是,Spring Boot + Security 会自动配置开箱即用的 CSRF,我们已经启用了它。因此,您可以两全其美。
注意:您可能需要进一步优化此配置以满足您的需求。
关于spring-boot - Spring Boot CSRF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929943/