I’ve an Angular 9 frontend + Java Spring Boot 2 backend software. I exploit JWT entry tokens in cookies to authenticate my customers and so I want XSRF cookies to guard in opposition to XSRF assaults. At the moment I carry out a GET
name to my server when my Angular software is loaded for the primary time, which can generate a XSRF cookie which then will get saved on the shopper. All works nice till…
Issues break once I logout as a result of I clear all cookies at that time. The primary (non-GET
) name to the server API will fail as a result of XSRF token is lacking, however second name will work as a result of the primary name retrieved a brand new XSRF token regardless of failing.
I figured it might be a good suggestion to implement a HTTP interceptor that checks each request for the server for the presence of the XSRF cookie. If not current, I’ll make a GET
name to the server only for the XSRF cookie after which proceed with the request. To stop that GET
name from being intercepted recursively I added an additional if verify to let the GET
name move like this:
intercept(request: HttpRequest<any>, subsequent: HttpHandler): Observable<HttpEvent<any>> {
if (this.csrfTokenNotPresent() && !this.isCsrfTokenRequest(request)) {
this.authService.getCsrfToken().subscribe((obj: any) => {
return subsequent.deal with(request);
});
}
if(this.csrfTokenNotPresent() && this.isCsrfTokenRequest(request)) {
return subsequent.deal with(request).pipe(
map((response: HttpResponse) => {
// TODO map XSRF token from response to ongoing request
})
);
}
return subsequent.deal with(request);
}
personal csrfTokenNotPresent(): boolean {
return !this.cookieService.verify('XSRF-TOKEN');
}
personal isCsrfTokenRequest(request: HttpRequest<any>): boolean {
return request.url != null && request.url === '/api/auth/csrf';
}
- The primary
if
block begins a brand newGET
request and waits for that to complete. - The second
if
block will catch that request, let the decision get to the server and may add the XSRF cookie from the response to the request within theTODO
placeholder - The primary
if
block ought to now proceed and the request now accommodates the XSRF cookie
I’m not fully certain this can work. Can I add cookies to an ongoing HTTP request? If that’s the case, how do I map the cookies from the HttpResponse
to the request? I’m additionally open to different approaches to resolve my drawback.