spring-boot - Spring Boot CSRF

标签 spring-boot csrf-protection

试图在最新的 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,我们已经启用了它。因此,您可以两全其美。

注意:您可能需要进一步优化此配置以满足您的需求。

Full Example on GitHub

关于spring-boot - Spring Boot CSRF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929943/

相关文章:

将war文件部署到webapps后,Java项目未从tomcat管理器在tomcat服务器上运行?

php - 跨站请求伪造

java - Spring MVC中的CSRF(跨站请求伪造)保护

php - admin内页使用CSRF重要吗?

angular - 如何将 csrf token 添加到 Angular 2 应用程序

java - AWS SES 在 Spring Boot Java 中实现,无需使用凭证

java - JOOQ 更新集未填充值

java - Spring Boot YAML 文件中的多个属性

java - SolrCrud存储库: use inheritance

laravel - Laravel 5.6-自耗API的Passport JWT httponly cookie SPA身份验证?