如何在spring上测试csrf保护?

z9ju0rcb  于 2021-08-20  发布在  Java
关注(0)|答案(0)|浏览(271)

如果我没有弄错的话,默认情况下,java配置会启用csrf保护。目前,在我的spring boot项目中,我创建了一个配置类,在其中我设置了一个控件,允许您禁用csrf保护,如下所示:

@EnableWebSecurity
@Configuration
@Order(value = Ordered.LOWEST_PRECEDENCE - 1987)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${security.enable.csrf}")
    private boolean csrfEnabled;

    @Override
    public void configure(WebSecurity web) {
        // exclude some services from authentication
        web.ignoring()
                .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/security",
                        "/swagger-ui.html", "/webjars/**", "/csrf", "favicon.ico", "/graphiql", "/vendor/**",
                        "/subscriptions", "/altair")
                .antMatchers(HttpMethod.OPTIONS, "/**").antMatchers(HttpMethod.GET, "/**")
                .antMatchers(HttpMethod.POST, "/**");
    }

    /* Disables CSRF */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().xssProtection().and().contentSecurityPolicy("script-src 'self'");

//      CSRF protection is enabled by default with Java configuration. 
//      If you would like to disable CSRF, the corresponding Java 
//      configuration can be seen below.
//      If you want to disable CSRF you have to set 
//      security.enable.csrf = false in application.yml
        if (csrfEnabled == false) {
            http.csrf().disable();
            logger.info("CSRF HAS BEEN DISABLE");
            // Else CSRF is enable
        } else {
            logger.info("CSRF IS ENABLE");
        }
    }
}

但如何检查csrf保护是否真的保持激活或停用?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题