I am looking to deploy an angular frontend app on gh-pages and deploy a springboot app on heroku so they will obviously be running on different servers. Default angular xsrf doesn't seem to be able to support this. Is there a clean way to auto handle all of the csrf cookies and headers or do I need to hack together a solution such as here? angular4 httpclient csrf does not send x-xsrf-token
Asked
Active
Viewed 597 times
1 Answers
1
Create a custom HttpInterceptor
and make sure to include it in the app.module as a provider.
Here is an example of a a similar class I use. You can replace the conditions in the If
Condition to match your specific use cases.
You can find out more about HTTP Interceptors in Angular Here
@Injectable({
providedIn: 'root'
})
export class AbsoluteurlCsrfHeaderInterceptorService implements HttpInterceptor {
constructor(
private tokenExtractor: HttpXsrfTokenExtractor,
private environment: Environment
) {}
// add application default headers to all requests
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headerName = 'X-CSRF-Token';
const token = this.tokenExtractor.getToken() as string;
let newReq = req.clone();
// because we are using aboslute paths in development mode
// we can't rely on the built in CSRF behavior
// if we are not in prod mode and the url is absolute (begins with http)
// add the csrf token if one exists
if ( !this.environment.production
&& this.environment.api_endpoint.length
&& ( req.url.substr(0, 4 ) === 'http' || req.url.substr(0, 5 ) === 'https')
&& token !== null
&& !req.headers.get(headerName)
) {
newReq = req.clone({headers: req.headers.set(headerName, token)});
}
return next.handle(newReq);
}
}

Edward
- 1,076
- 1
- 12
- 24
-
Not seeing it in the docs but I assume HttpXsrfTokenExtractor automatically keeps track of the latest CSRF-Token and isn't something I need to be worried about? – yodigi7 May 11 '21 at 17:11
-
as long as you are using the same interceptors throughout your app, i.e. defined in the AppModule, then you should be fine. – Edward May 11 '21 at 17:14
-
Does it even make sense to have csrf token if I am going to allow other sites to be able to see and use it (setting sameSite=None and Secure)? Seems like just the nature of the cross-site talking between gh-pages and heroku makes any crsf security a moot point. – yodigi7 May 11 '21 at 23:46