CSRF token validation failed : Retrofict Post

623 views Asked by At

I'm developing an Android app and I need to POST data to a service (SAP Hybris marketing).

For doing that I first get the CSRF token from the service and then I try to post JSON data using the token for authenticate.

This is my code:

public interface APIService {

@POST("CUAN_IMPORT_SRV/ImportHeaders")
@Headers("Content-Type: application/json")
Call<String> savePost(@Header("Authorization") String bearer, @Header("X-CSRF-Token") String token, @Body String jsonContact);

@GET("CUAN_IMPORT_SRV/")
Call<String> getCall(@Header("Authorization") String bearer, @Header("X-CSRF-Token") String token ) ;

}

public void sendGet(final JSONObject jsonObject) {

    mAPIService.getCall("Basic mybasicauthenticationtoken", "Fetch").enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {

            if(response.isSuccessful()) {
                System.out.println(response.headers().get("X-CSRF-Token"));
                Log.i(TAG, "get submitted to API." );

                token = response.headers().get("X-CSRF-Token");
                Log.i(TAG, "TOKEN = " + token );

                mAPIService.savePost("Basic mybasicauthenticationtoken", token, jsonObject.toString()).enqueue(new Callback() {
                    @Override
                    public void onResponse(Call call, Response response) {


                        if(response.isSuccessful()) {
                            System.out.println(response.body().toString());
                            Log.i(TAG, "post submitted to API." + response.body().toString());
                        }
                        try {
                            System.out.println(response.errorBody().string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call call, Throwable t) {
                        System.out.println("ERROR POST");
                        Log.e(TAG, "Unable to submit post to API.");
                    }
                });
            }
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            Log.e(TAG, "Unable to submit get to API.");
           t.printStackTrace();
        }
    });

the GET call works correctly and gave me the token:

I/ContentValues: get submitted to API. TOKEN = lV6pgxm6m3qw9uGh5ZcaRg==

But then, when I try to post data I get the following message:

I/System.out: CSRF token validation failed

Can someone help me with this issue?

0

There are 0 answers