【发布时间】:2018-01-27 16:35:57
【问题描述】:
我有一个 Spring boot RESTful 服务,其 Spring 安全配置如下:
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().and()
/*.formLogin().loginPage("/auth")
.permitAll().and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and().httpBasic().and()*/
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class);
}
&
public class CsrfHeaderFilter extends OncePerRequestFilter {
private static final String CSRF_COOKIE_NAME = "XSRF-TOKEN";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
response.addHeader("X-CSRF-TOKEN", csrf.getToken());
Cookie cookie = WebUtils.getCookie(request, CSRF_COOKIE_NAME);
String token = csrf.getToken();
if (cookie == null || token != null && !token.equals(cookie.getValue())) {
cookie = new Cookie(CSRF_COOKIE_NAME, token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
}
我正在使用 Angular 4(最新版本)调用 RESTful 服务。它正在发出一个抱怨并抛出 403 Forbidden “无法验证提供的 CSRF 令牌,因为找不到您的会话”。这是预期的,因为我在发送 post 请求时没有设置 X-CSRF-TOKEN 标头,但此标头确实存在:- 设置 Cookie:XSRF-TOKEN=;路径=/
角度:
auth.service.ts:
const body = 'SOMERANDOMKEY1111';
const headers = new HttpHeaders().set('Content-Type', 'application/json').set('withCredentials', 'true');
return this._http.post(this.endpoint + this.auth, body, {
headers: headers
});
app.module.ts(注意:使用 HttpClient 进行 post 请求):
providers: [ ...
{
provide: XSRFStrategy, useFactory: xsrfFactory
}...]
export function xsrfFactory() {
return new CookieXSRFStrategy('XSRF-TOKEN', 'XSRF-TOKEN');
}
我已关注 this 并阅读了文档,但似乎无法正常工作。
【问题讨论】:
-
角码在哪里?
-
用角码更新。
-
我已经在设置 withCredentials 标题但仍然无法正常工作。