2

I am creating a set of API endpoints for a mobile app using Rest. For User authentication, I am using the default API endpoints supplied by Drupal. That would be

/user/logout?_format=json&token=<logout_token obtained from login api response.>

I wanted to remove the _format=json from the URL parameter and so I created a custom route with the existing controller just for this purpose. However, I am getting an error.

"'csrf_token' URL query argument is invalid

I am not able to figure out how to remove this error. I had added a csrf_token as an additional parameter with the one I got from successful login. It seems however that the csrf token being validated against is generated somewhere else.

I can remove this error by removing the csrf token entry from the routing file entry but that would be a security violation. How do we fix this error or is there a better way to handle the user logout api endpoint.

2 Answers 2

1

To get the right csrf_token you should first request /session/token this route coming from system.routing.yml so in your controller action add those two things:

  1. Get the system csrf_token from /session/token
  2. Add your csrf token to header request as X-CSRF-Token

Update: If you are using rest module you should get the csrf token from /rest/session/token instead of /session/token

3
  • 2
    Hi. I've tried this solution but It doesn't work for me. I always get the error. I've tried with csrf-token got on login and with the one requested with session/token, but none of them work. Always the same error.
    – briast
    Jun 1, 2021 at 15:56
  • Ive also tried this and getting same error whether i use login reply token or session token. calling it /session/token is also bad labelling if its a csrf token. Jan 27, 2022 at 11:50
  • There's no rest/session/token, at least not in Drupal 10 now. session/token gives the same error, as well as using the original token from your login.
    – Gábor
    Aug 25, 2023 at 21:13
2

You can use POST method on /user/logout without params and token, the cookie will be deleted so the user will be logged out, but in the server-side Drupal will not destroy the session, so you'll end up by having a lot of unused sessions...

I wonder why do you want to remove the _format=json from the URL ?

1
  • 1
    I wanted to provide a cleaner url. The _format=json is not required in our case as it is a partially decoupled system. The parameter is only to differentiate between HTML and JSON logins which is useful for stock Drupal site but looks bad in our case. I am using post method but I am always getting csrf error.
    – Binny
    May 29, 2020 at 4:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.