postodatacsrfabapsap-gateway

CSRF error after create entity POST request in ABAP OData service


I am about to learning OData Services in ABAP for working purposes. Implementing the create entity request I run into some issues.

METHOD airportsset_create_entity.

****************************************************
* VARIABLES
****************************************************

    DATA:
      lt_wa_input_data LIKE er_entity,
      lt_wa_airport    TYPE zt_xy_airport,
      lv_max_id        TYPE zd_xy_id.

****************************************************
* METHOD LOGIC
****************************************************

    " Get the data from the post request body.
    CALL METHOD io_data_provider->read_entry_data
      IMPORTING
        es_data = lt_wa_airport.

    " Copy data into the work area.
    MOVE-CORRESPONDING lt_wa_input_data TO lt_wa_airport.

    " Select the max id from the table to prevent duplicate key error.
    SELECT SINGLE MAX( airport_id ) FROM zt_xy_airport INTO lv_max_id.

    " Fill out the remaining fields of the work area.
    lt_wa_airport-mandt = sy-mandt.
    lt_wa_airport-airport_id = lv_max_id + 1.

    " Insert the data to the table.
    INSERT zt_kd_airport FROM lt_wa_airport.

  ENDMETHOD.

Calling this POST request I got back this error:

CSRF token validation failed

I know that I have to get the token from a get request header, but when I try to insert that token into the POST request header nothing seem to be working. Got back the same error.

I am working in SAP LOGON 770.


Solution

  • The POST request must be preceded by a HEAD request to the same endpoint (or a GET request to the service's base URL) which includes the header

    X-CSRF-Token: Fetch
    

    The response to this HEAD (or GET) request will then contain a CSRF token in the X-CSRF-Token header, and it will contain

    • a session cookie SAP_SESSIONID_<SID>_<client>, to which this token is bound,
    • or, if there is no session, a sap-XSRF_<SID>_<client> cookie, to which this token is bound.

    Whether there is a session depends on the authentication mechanism that you chose. But in any case, both the cookie and the X-CSRF-Token header must be included in the POST request.

    Likely, you have to make a change in the code that makes the request (which you have not shared).