我正在开发一个具有Angular2前端的RESTful Spring后端。我将我的访问令牌(JWT实现)存储在一个httpOnly Cookie中。为了保护自己免受post请求的XSRF攻击,我需要在除登录页面之外的所有页面上启用XSRF保护。根据Spring Security guide here,我已经启用了CookieCsrfTokenRepository。
但是,当我遇到一个公共API (GET)时,XSRF-TOKEN没有被设置。另外,当我从Angular2提交我的登录表单数据时,系统会提示一个“invalid csrf token”错误。下面是我的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);发布于 2017-01-24 19:07:18
您不应该通过HTTP GET获取CSRF令牌,请参阅Spring Security Reference
使用正确的HTTP动词
防御CSRF攻击的第一步是确保你的网站使用正确的HTTP动词。具体地说,在使用Spring Security的CSRF支持之前,您需要确保您的应用程序对任何修改状态的操作都使用了PATCH、POST、PUT和/或DELETE。
这不是Spring Security支持的限制,而是对适当的CSRF预防的一般要求。原因是在HTTP GET中包含私有信息可能会导致信息泄露。有关使用POST而不是GET处理敏感信息的一般指导,请参阅RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI’s。
您不应将登录排除在CSRF保护之外,请参阅Spring Security Reference。
中的
日志记录
为了防止伪造登录请求,表单中的登录也应该受到CSRF攻击的保护。
但是您可以排除一些URL,并包含一些HTTP动词来保护CSRF,请参阅Spring Security Reference
CSRF您还可以指定一个自定义RequestMatcher来确定哪些请求受CSRF保护(例如,您可能不关心注销是否被利用)。简而言之,如果Spring Security的CSRF保护没有完全按照您想要的方式运行,您可以自定义该行为。有关如何使用XML进行这些定制的详细信息,请参阅Section 41.1.18, “”文档,而使用CsrfConfigurer配置时如何进行这些定制的详细信息,请参阅javadoc。
发布于 2017-05-24 03:03:37
您是否尝试过启用withCredentials: true?这就是我在Angular2中编写帖子服务器的方式。
this.http.request(
path,
{
method: RequestMethod.Post,
body: body,
headers: customHeaders,
withCredentials: true
}
)
.map...
.catch...我在WebSecurityConfig中也有相同的配置。我确实有一个使用Angular 2和Spring Boot的工作示例,该示例使用CookieCsrfTokenRepository。
Github repo:angular-spring-starter
https://stackoverflow.com/questions/41823108
复制相似问题