Spring Boot CSRF [英] Spring Boot CSRF

查看:84
本文介绍了Spring Boot CSRF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图在最新的Spring Boot上实现CSRF保护.互联网上的所有示例均基于用户登录和身份验证,我不需要.

Tried to implement CSRF protection on the latest Spring Boot. All the examples on internet are based on user login and authentication, which I do not need.

我的网站没有任何需要身份验证的部分.我想要

My site does not have any sections requiring authentication. I would like

1)休息请求来自站点内部.不允许外部直接要求使用wget.

1) Rest requests come from within site. No direct request from outside with wget to be allowed.

2)必须从索引页面(/)请求所有页面(路由)

2) All pages (routes) must be requested from the index page (/)

将安全性依赖项包含在 pom.xml

Included the security dependency in pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

-在 application.properties 中定义的用户(尽管我不需要)

-- Defined users in application.properties (even though, I do not need)

-应用创建 _csrf.token .

-创建的类扩展了 WebSecurityConfigurerAdapter 并覆盖了"configure"方法.

-- Created class extending WebSecurityConfigurerAdapter with "configure" method overriding.

在配置"中尝试了所有建议的过滤器.它没有用,最后留空了.

Tried all suggested filters in "configure". It did not work and finally left it blank.

问题在于Wget可以直接获取api页面.如何预防呢?

The problem is that Wget can get api pages directly. How to prevent it?

推荐答案

我很快将这种配置的POC放在一起:

I've quickly put together a POC of this configuration:

@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,而我们仍然启用了它.因此,您可以两全其美.

The gist of it is Spring Boot + Security will secure all endpoints automatically. Here we explicitly allow requests to all endpoints. But, Spring Boot + Security automatically configures CSRF out of the box which we've left enabled. Thus you get the best of both worlds.

注意:您可能需要进一步完善此配置,以满足您的需求.

NOTE: You'll probably need to refine this configuration further to meet your needs.

GitHub上的完整示例

这篇关于Spring Boot CSRF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆