【问题标题】:Spring Security denies logout CSRF tokenSpring Security 拒绝注销 CSRF 令牌
【发布时间】:2015-08-25 17:05:54
【问题描述】:

我正在尝试使用本教程实现一个 Angular 应用程序:https://spring.io/guides/tutorials/spring-security-and-angular-js/

登录并执行后续的 HTTP 调用也可以。 Angular 成功附加了 CSRF 令牌,Spring 成功解析了它。假设令牌是foo,请求将包含以下标头:

Cookie:JSESSIONID=...; XSRF-TOKEN=foo

X-XSRF-TOKEN:foo

现在,当尝试使用 $http.post('logout', {}),Angular 将使用完全相同的标头。但是,Spring 以 403 回答:

在请求参数“_csrf”或标头“X-CSRF-TOKEN”上发现无效的 CSRF 令牌“null”。

这是我的安全配置的样子:

protected void configure(HttpSecurity http) throws Exception {
    http
        .httpBasic().and()
        .authorizeRequests()
        .antMatchers("/").permitAll()
        .anyRequest().authenticated().and()
        .logout().and()
        .addFilterBefore(new CsrfHeaderFilter(), CsrfFilter.class);
}

CsrfHeaderFilter 是 explained in the tutorial 类(显然适用于所有其他请求)。

【问题讨论】:

    标签: java angularjs spring spring-mvc spring-security


    【解决方案1】:

    我意识到这已经晚了 2 个月,但我今天遵循完全相同的指南,并且这个未答复的帖子不断弹出,所以这里是解决方案。

    基本上,您在HttpSecurity 配置器中缺少csrfTokenRepository() 配置。

    Spring CsrfTokenRepository 需要标头 "X-CSRF-TOKEN",但 Angular 在名为 "X-XSRF-TOKEN" 的标头中发送令牌,因此 the guide 建议您设置 CsrfTokenRepository 的实例,它需要 Angular 默认标头 "X-XSRF-TOKEN"

    protected void configure(HttpSecurity http) throws Exception {
        http
            .httpBasic().and()
            .authorizeRequests()
            .antMatchers("/").permitAll()
            .anyRequest().authenticated().and()
            .logout()
            .and()
            //This is the first part you were missing
            .csrf()
                .csrfTokenRepository(csrfTokenRepository())
            .and()
                .addFilterBefore(new CsrfHeaderFilter(), CsrfFilter.class);
    }
    
    
    @Bean
    public CsrfTokenRepository csrfTokenRepository(){
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    
        // This is the second part you were missing
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-07
      • 1970-01-01
      • 2012-03-06
      • 2019-07-20
      • 2015-06-13
      • 2020-10-19
      • 2014-08-10
      • 2014-12-06
      • 2013-08-28
      相关资源
      最近更新 更多