Friday, 28 August 2020

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

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?



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

1 comment:

  1. Hi hemant,

    I am also facing the same issue.
    Please advise, how this issue was resolved.
    Handling CSRF for mobile cordova+angular. Your inputs would help me.

    ReplyDelete