I've got a Spring boot RESTful service with Spring security configured like so:
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);
}
}
I'm invoking the RESTful service using Angular 4 (latest version). It's doing a post request an complaining and throwing a 403 Forbidden "Could not verify the provided CSRF token because your session was not found." Which is expected because I when sending the post request the X-CSRF-TOKEN header is not being set but this header does exist:- Set-Cookie:XSRF-TOKEN=; Path=/
Angular:
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 (note: using HttpClient for post request):
providers: [ ...
{
provide: XSRFStrategy, useFactory: xsrfFactory
}...]
export function xsrfFactory() {
return new CookieXSRFStrategy('XSRF-TOKEN', 'XSRF-TOKEN');
}
I've followed this and read up on the docs but can't seem to get this working.