How to handle X-CSRF-TOKEN correctly in an angular-based cordova app?

Viewed 801

I have an Angular (v10) WebApp, which handles the X-CSRF-TOKEN cookie correctly as explained in the Angular Guide by using the HttpClientXsrfModule in my imports, i.e.:

  // app.module.ts
HttpClientModule,
HttpClientXsrfModule.withOptions({
  cookieName: 'XSRF-TOKEN',
  headerName: 'X-XSRF-TOKEN',
}),

and by setting an relative Path in my services' requests, like:

  // some service.ts
  public deleteX(x_id: number): Observable<any> {
      return this.httpClient.delete(`api/X/${x_id}`);
  }

and now, the browser itself handles fetching the token from the server and sending it by each subsequent POST/DELETE/PUT/PATCH request successfully.

However, if I compile the application now to an Android app using cordova, the app sends a request (with x_id=1068) to file:///android_asset/www/api/X/1068. I can modify my http services to use platform-specific absolute/relative paths easily, such as:

  // some service.ts
  public deleteX(x_id: number): Observable<any> {
    if (this.cordovaService.platform === CordovaService.PLATFORM_ANDROID) {
      return this.httpClient.delete(`${environment.baseUrl}/api/X/${x_id}`);
    } else {
      return this.httpClient.delete(`api/X/${x_id}`);
    }
  }

But then, my request's response from the Android application is

error: "access_denied"
error_description: "Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'."

What can I do, to add correct handling of the X-XSRF-TOKEN for my cordova compiled Android app?

1 Answers

I ended up using the cordova-plugin-advanced-http, that is offering a response-cookie-fetching opportunity described here. I've created a generic-http-service containg generic methods for each of the HTTP methods (GET,HEAD,PATCH,PUT,POST,DELETE), that is first checking for the running platform and then forwarding an adjusted request.

example for generic GET (pseudo-code):

// generic-http-service.ts
   
public get<T>(url: string, queryParams?: any): Observable<T> {
   if (this.cordovaService.platform === CordovaService.PLATFORM_ANDROID) {
       // android-specific solution
       // 1. adjust params
       // 2. set general headers + the XSRF-TOKEN from the previous sendt request
       // 3. return Observable(obs) {
       // 4. send:
       cordova.plugin.http.get(`${environment.baseUrl}/${url}`, adjustedParams, adjustedHeaders, 
              successResponse => { 
                  // 5. fetch & save XSRF-TOKEN
                  obs.next(JSON.parse(successResponse.data) as T);
              }, errorResponse => { 
                  obs.error(errorResponse);
              })
       }
   } else {
       // web-specific solution based on the angular guide
       return this.httpClient.get(`${url}`);
   }
}

Afterwards I just needed to adjust my services a little bit.

Related