wikipediawikipedia-apiwikimediapywikibotwikimedia-commons

Why does the CSRF token from the Wikimedia API only work for 1-2 hours after login, then stop working?


I am using the Wikimedia API with Basic Authorization and Cookie-based authentication. Initially, after logging in, I can retrieve the CSRF token without issues. However, after about 1-2 hours, any request for a new CSRF token only returns the following response:

"query": {
    "tokens": {
        "csrftoken": "+\\"
    }
}

If I log in again, I can retrieve the CSRF token, but this issue keeps recurring after a while.

What I've tried so far:

  1. Checking that the Cookie being sent is the same as when I initially logged in.
  2. Including all necessary headers (including Cookie).
  3. Re-logging in to obtain a new token.

Does anyone know why the CSRF token stops working or changes like this? Could it be related to the Cookie sent in the headers?


Solution

  • CSRF tokens are stored in the session, which expires after one hour of inactivity. If you have logged in using the "keep me logged in" option, your login should survive that, and you can just request a new token.

    In general, receiving an anonymous token (+\) means you are not logged in anymore. You can use assertions to make session expiry less surprising.