cancel
Showing results for 
Search instead for 
Did you mean: 

Error CSRF Token Validation Failed in POST API

VB_devloper
Discoverer
0 Kudos
182

Hi Experts,

I am getting error "CSRF Token Validation Failed" in POST API. 

I am able to generate CSRF token successfully through below code. But seems token is not getting set hence getting the above error. 

Please suggest where I am doing wrong. Also, I am able to post successfully via POSTMAN with same data and Basic Authentication.

Many Thanks

DATA(lv_string) = cl_web_http_utility=>encode_base64( lv_Str ).

 

lv_string = |Basic { lv_string }|.

** Set up header fields for getting X_CSRF-TOKEN

DATA(lo_request2) = lo_http_client->get_http_request( ).

lo_request2->set_header_fields( VALUE #(

( name = 'Content-Type' value = 'application/json' )

( name = 'X-CSRF-Token' value = 'fetch' )

( name = 'Authorization' value = lv_string )

 

 

) ).

 

CONCATENATE i_url1 '/sap/opu/odata/sap/API_MAINTNOTIFICATION/MAINTENANCENOTIFICATION' INTO i_url2.

lo_request2->set_uri_path( i_uri_path = i_url2 ).

DATA(lv_response2) = lo_http_client->execute( i_method = if_web_http_client=>get )->get_header_fields( ).

READ TABLE lv_response2 INTO DATA(ls_repsonse2) WITH KEY name = 'x-csrf-token'.

IF sy-subrc = 0.

DATA(lv_token) = ls_repsonse2-value.

CLEAR ls_repsonse2.

ENDIF.

 

IF lv_token IS NOT INITIAL.

 

** Set CSRF Token

lo_http_client->set_csrf_token( ).

 

 

" Navigate to the resource and create a request for the create operation

lo_request = lo_client_proxy->create_resource_for_entity_set( 'MAINTENANCE_NOTIFICATION' )->create_request_for_create( ).

 

 

ENDIF.

 

 

Sandra_Rossi
Active Contributor
Please use the buttons "..." and "</>" to display your code nicely. See how to do it here: https://community.sap.com/t5/questions-about-sap-websites/how-to-post-code-in-sap-community-gt-2024/...
Sandra_Rossi
Active Contributor
0 Kudos
For x-csrf-token, you need one requests to "fetch" the x-csrf-token, then you can do the next requests by initializing the header field x-csrf-token. It's clear that your code is incomplete, why are you not passing any token to "set_csrf_token"?

Accepted Solutions (0)

Answers (1)

Answers (1)

VB_devloper
Discoverer
0 Kudos

Hi Sandra,

I am fetching csrf token successfully. Could you please guide me where I am missing to pass token to lo_http_client->set_csrf_token( ).

Thanks in advance!

Sandra_Rossi
Active Contributor
0 Kudos
Let's say you have fetched the token into your variable MY_TOKEN, then you should call lo_http_client->set_csrf_token( MY_TOKEN ). How do you want the request to contain the token otherwise? NB: I don't know the method SET_CSRF_TOKEN of CL_HTTP_CLIENT, it doesn't exist in 7.40 SP8. By the way, I can't read correctly the code in your question, it's badly formatted, that would be great if you edit your question and format the code as explained in the link given above.