Search code examples
pythonmediawiki-api

Unable to login when using the MediaWiki API


I would like create new user accounts in my local MediaWiki using the MediaWiki API using a simply Python script.

Based on the documentation, it is my understanding that I must first login as an administrator to have the privilege needed for the user creation.

I use some code like this to login:

import requests

def login(base_url: str):
    session = requests.Session()

    url = base_url + "/api.php"

    # Retrieve login token first
    print(f"Get login token...")
    response = session.get(url=url, params={
        'action':"query",
        'meta':"tokens",
        'type':"login",
        'format':"json"
    })
    data = response.json()
    login_token = data['query']['tokens']['logintoken']
    print(f"login_token={login_token}")

    print(f"Login...")
    response = requests.post(url, data={
        'action': 'login',
        'lgname': 'admin',
        'lgpassword': 'admin_password',
        'lgtoken': login_token,
        'format': 'json',
    })
    login_data = response.json()
    print(login_data)

where admin is the administrator account I specified during the original configuration of MediaWiki.

Unfortunately the result is {'login': {'result': 'Failed', 'reason': 'Unable to continue login. Your session most likely timed out.'}}.

What am I missing or how can I debug this problem?


Solution

  • Narrowly, the problem is that you are using requests.post instead of session.post (so you lose the session, as pointed out by the error message). But what you really want to do is create an owner-only OAuth 2 app with the Create accounts grant, and then add the Authorization header to the API requests you make.

    If the wiki does not support OAuth, you should use a bot password; that will use the same login flow as in the question, but it's more robust (bot password logins are guaranteed to work via the login API endpoint, normal logins aren't). Plus, you won't have to store a sensitive password along with the bot code.