将AngularJS与SpringSecurity3.2一起用于CSRF

时间:2014-06-03 19:04:06

标签: angularjs spring-security csrf csrf-protection

AngularJS

的index.html

<head>
    <meta name="_csrf" content="${_csrf.token}"/>
    <!-- default header name is X-CSRF-TOKEN -->
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
</head>

SpringSecurity 3.2

Spring使用 HttpSessionCsrfTokenRepository ,默认情况下为CSRF提供头名称为 X-CSRF-TOKEN ,但Anuglar约定 X-XSRF-TOKEN

我想扩展 HttpSessionCsrfTokenRepository 并覆盖标题名称,但由于它标记为final,我最终实现了自定义令牌存储库。

@Component
public class CustomCsrfTokenRepository implements CsrfTokenRepository {

  public static final String CSRF_PARAMETER_NAME = "_csrf";

  public static final String CSRF_HEADER_NAME = "X-XSRF-TOKEN";

  private final Map<String, CsrfToken> tokenRepository = new ConcurrentHashMap<>();

  public CustomCsrfTokenRepository() {
    log.info("Creating {}", CustomCsrfTokenRepository.class.getSimpleName());
  }

  @Override
  public CsrfToken generateToken(HttpServletRequest request) {
    return new DefaultCsrfToken(CSRF_HEADER_NAME, CSRF_PARAMETER_NAME, createNewToken());
  }

  @Override
  public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
    String key = getKey(request);
    if (key == null)
      return;

    if (token == null) {
      tokenRepository.remove(key);
    } else {
      tokenRepository.put(key, token);
    }
  }

  @Override
  public CsrfToken loadToken(HttpServletRequest request) {
    String key = getKey(request);
    return key == null ? null : tokenRepository.get(key);
  }

  private String getKey(HttpServletRequest request) {
    return request.getHeader("Authorization");
  }

  private String createNewToken() {
    return UUID.randomUUID().toString();
  }
}

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Inject
    private CustomCsrfTokenRepository customCsrfTokenRepository;


     @Override
        protected void configure(HttpSecurity http) throws Exception {

            http
    //          .addFilterAfter(new CsrfTokenGeneratorFilter(), CsrfFilter.class)
                .exceptionHandling()
                    .authenticationEntryPoint(authenticationEntryPoint)
                    .and()
                .formLogin()
                    .loginProcessingUrl("/app/authentication")
                    .successHandler(ajaxAuthenticationSuccessHandler)
                    .failureHandler(ajaxAuthenticationFailureHandler)
                    .usernameParameter("j_username")
                    .passwordParameter("j_password")
                    .permitAll()
                    .and()

                 .csrf()
                    .csrfTokenRepository(customCsrfTokenRepository)
                    .and()
              }
           }
  1. 如何干净地覆盖标题名称而不是创建自定义csrfTokenRepository?

  2. 我是否需要对单页进行其他配置更改 诸如AngularJS之类的应用程序,因为它还不起作用。

1 个答案:

答案 0 :(得分:11)

在Spring Security中使用Java配置时,应该可以:

  public void configure(final HttpSecurity http) throws Exception
  {
    final HttpSessionCsrfTokenRepository tokenRepository = new HttpSessionCsrfTokenRepository();
    tokenRepository.setHeaderName("X-XSRF-TOKEN");

    http.csrf().csrfTokenRepository(tokenRepository);
  }

复杂的是,单页应用程序依赖于AJAX,并且包含带有AJAX请求的CSRF令牌有点复杂。使用AngularJS时,服务器应在第一次请求时以及用户登录或注销时发送名为XSRF-TOKEN的会话cookie。然后,AngularJS将在HTTP标头X-XSRF-TOKEN中返回此cookie的值以及所有请求,然后服务器可以检查这些请求。