I am writing a code to use the MediaWiki web service API to login to the system. Based on the online API documentation, I used “action=query” to get a login token and “action=clientlogin” to post the login request, but I got “Invalid CSRF token” error. I am not sure what I missed, is there a clientlogin sample code, either html or php or any format?
Clientlogin web service API


What I remember from playing with the web service API a while ago is that I was running into the same error due to a session cookie issue. A related topic is here: https://www.mediawiki.org/wiki/API_talk:Login#action=clientlogin. Also, not the best piece of code, but an example that I wrote which partially worked is here.

Yeah, it means you are dropping the session. Clients are expected to handle cookies.
mwapi has a good example of using that API.

thank you so much for the sample code, I will take a look.

well, I turned on the allow cookies option and I can see the cookies are kept from the browser and sent back to the web server. The error message said invalid token, but the token was sent by the query token API.

my code is JavaScript running in the browser, the cookies are managed by browser and they are passed from webserver and sent back to the web server as well. I can see the session id is the same between “query token” post and “client login” post. I will post my code the API mail list. Thank you so much for your help.

My other guess would be lack of proper URL encoding for the token. But yeah, it would be easier to help if we can see the code.

Yes, you are right. I added URL encoding and it is working now. As you suggested, I created a small githut project for the test caseMediaWiki REST API Test Case in HTML/JavaScript
my test code is in HTML/JavaScript in case other developers may have the similar issues.

Hello @renwang101, and thanks for sharing your test case in Javascript. For connecting to Mediawiki API in general I tend to use a Nodejs wrapper for Mediawiki called Nodemw. It’s fairly easy to use and I have had good results with it during various tasks: bulk uploads, image description update, etc. An example of a recent task on Github.