Search code examples
angularcsrf

CSRF using absolute URL - Angular


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


Solution

  • 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);
      }
    
    }