【发布时间】:2026-01-20 21:10:01
【问题描述】:
我正在开发一个带有 Angular2 前端的 RESTful Spring 后端。我将访问令牌(JWT 实现)存储在 httpOnly Cookie 中。为了保护自己免受对 post 请求的 XSRF 攻击,我需要在所有页面上启用 XSRF 保护,登录页面除外。根据 Spring Security 指南here,我启用了CookieCsrfTokenRepository。
但是,当我点击公共 API (GET) 时,XSRF-TOKEN 未设置。此外,当我从 Angular2 提交登录表单数据时,系统会出现“无效的 csrf 令牌”错误。下面是我的WebSecurityConfig:
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.exceptionHandling()
.authenticationEntryPoint(this.authenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(TOKEN_REFRESH_ENTRY_POINT).permitAll() // Token refresh end-point
.antMatchers(TOKEN_CSRF_ENTRY).permitAll()
.and()
.authorizeRequests()
.antMatchers(TOKEN_BASED_AUTH_ENTRY_POINT).authenticated() // Protected API End-points
.and()
.cors()
.and()
.addFilterBefore(buildAjaxLoginProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class);
【问题讨论】:
标签: spring spring-mvc spring-security