API:Login

From MediaWiki.org
Jump to navigation Jump to search

Other languages:
Deutsch • ‎English • ‎español • ‎français • ‎italiano • ‎polski • ‎sicilianu • ‎български • ‎русский • ‎українська • ‎հայերեն • ‎العربية • ‎فارسی • ‎中文 • ‎文言 • ‎日本語 • ‎한국어

POST Request to login

MediaWiki API may require your application or client to provide authenticated user credentials and login for a) querying information or data-modifying actions b) making large queries with a higher request-per limit.

Two methods to authenticate[edit]

There are two ways to authenticate to the MediaWiki Action API:

Method 1. login[edit]

Bot and other non-interactive applications should use owner-only OAuth consumers if available as it is more secure. If not available or not applicable to the client, the login action may be used with bot passwords.

API documentation[edit]




action=login (lg)

(main | login)
  • This module only accepts POST requests.
  • Source: MediaWiki
  • License: GPL-2.0-or-later

Log in and get authentication cookies.

This action should only be used in combination with Special:BotPasswords; use for main-account login is deprecated and may fail without warning. To safely log in to the main account, use action=clientlogin.

Parameters:
lgname

User name.

lgpassword

Password.

lgdomain

Domain (optional).

lgtoken

A "login" token retrieved from action=query&meta=tokens

Example[edit]

POST Request[edit]

Note: lgtoken in the request above is retrieved from API:Tokens

Response[edit]

{  
   "login": {  
      "lguserid": 21,
      "result": "Success",
      "lgusername": "William"
   }
}

Sample code[edit]

login.py

#!/usr/bin/python3

"""
    login.py

    MediaWiki Action API Code Samples
    Demo of `Login` module: Sending post request to login
    MIT license
"""

import requests

S = requests.Session()

URL = "https://mediawiki.org/w/api.php"

# Retrieve login token first
PARAMS_0 = {
    'action':"query",
    'meta':"tokens",
    'type':"login",
    'format':"json"
}

R = S.get(url=URL, params=PARAMS_0)
DATA = R.json()

LOGIN_TOKEN = DATA['query']['tokens']['logintoken']

print(LOGIN_TOKEN)

# Send a post request to login. Using the main account for login is not
# supported. Obtain credentials via Special:BotPasswords
# (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword

PARAMS_1 = {
    'action':"login",
    'lgname':"your_bot_username",
    'lgpassword':"your_bot_password",
    'lgtoken':LOGIN_TOKEN,
    'format':"json"
}

R = S.post(URL, data=PARAMS_1)
DATA = R.json()

print(DATA)

Note: As of MediaWiki v1.27, using the main account for login is not supported. Obtain credentials via Special:BotPasswords or use clientlogin method. Logging in and remaining logged in requires correct HTTP cookie handling by your client on all requests. In the above example, we are showing how a session object requests.Session()helps persist cookies.

Method 2. clientlogin[edit]

Interactive applications such as custom editors or patrolling applications that provide a service without intending to fully replace the website or mobile apps that aim to completely replace access to the web-based user interface should use the clientlogin action. However, one should prefer using OAuth if it is available for authenticating the tool, as it is easier and more secure. This module is available since MediaWiki v1.27

API documentation[edit]




action=clientlogin (login)

(main | clientlogin)
  • This module only accepts POST requests.
  • Source: MediaWiki
  • License: GPL-2.0-or-later

Log in to the wiki using the interactive flow.

The general procedure to use this module is:

  1. Fetch the fields available from action=query&meta=authmanagerinfo with amirequestsfor=login, and a login token from action=query&meta=tokens.
  2. Present the fields to the user, and obtain their submission.
  3. Post to this module, supplying loginreturnurl and any relevant fields.
  4. Check the status in the response.
    • If you received PASS or FAIL, you're done. The operation either succeeded or it didn't.
    • If you received UI, present the new fields to the user and obtain their submission. Then post to this module with logincontinue and the relevant fields set, and repeat step 4.
    • If you received REDIRECT, direct the user to the redirecttarget and wait for the return to loginreturnurl. Then post to this module with logincontinue and any fields passed to the return URL, and repeat step 4.
    • If you received RESTART, that means the authentication worked but we don't have a linked user account. You might treat this as UI or as FAIL.
Parameters:
loginrequests

Only use these authentication requests, by the id returned from action=query&meta=authmanagerinfo with amirequestsfor=login or from a previous response from this module.

Separate values with | or alternative. Maximum number of values is 50 (500 for bots).
loginmessageformat

Format to use for returning messages.

One of the following values: html, wikitext, raw, none
Default: wikitext
loginmergerequestfields

Merge field information for all authentication requests into one array.

Type: boolean (details)
loginpreservestate

Preserve state from a previous failed login attempt, if possible.

Type: boolean (details)
loginreturnurl

Return URL for third-party authentication flows, must be absolute. Either this or logincontinue is required.

Upon receiving a REDIRECT response, you will typically open a browser or web view to the specified redirecttarget URL for a third-party authentication flow. When that completes, the third party will send the browser or web view to this URL. You should extract any query or POST parameters from the URL and pass them as a logincontinue request to this API module.

logincontinue

This request is a continuation after an earlier UI or REDIRECT response. Either this or loginreturnurl is required.

Type: boolean (details)
logintoken

A "login" token retrieved from action=query&meta=tokens

This parameter is required.
*
This module accepts additional parameters depending on the available authentication requests. Use action=query&meta=authmanagerinfo with amirequestsfor=login (or a previous response from this module, if applicable) to determine the requests available and the fields that they use.
Examples:
Start the process of logging in to the wiki as user Example with password ExamplePassword.
api.php?action=clientlogin&username=Example&password=ExamplePassword&loginreturnurl=http://example.org/&logintoken=123ABC [open in sandbox]
Continue logging in after a UI response for two-factor auth, supplying an OATHToken of 987654.
api.php?action=clientlogin&logincontinue=1&OATHToken=987654&logintoken=123ABC [open in sandbox]

Example 1: Process for a wiki without special authentication extensions[edit]

POST Request[edit]

Obtain token login in the request above via API:Tokens.

Response[edit]

{  
   "clientlogin":{  
      "status":"PASS",
      "username":"William"
   }
}

Sample code[edit]

Example 2: Process for a wiki with special authentication extensions[edit]

A wiki with special authentication extensions such as ConfirmEdit (captchas), OpenID, OATHAuth (two factor authentication), may have a more complicated authentication process. Specific fields might also be required in that case, the description of which could be fetched from the API:Authmanagerinfo query.

Step 1: Answer the Captcha and select OpenID authentication[edit]

Note: The client would be expected to redirect the user's browser to the provided redirecttarget. The OpenID provider would authenticate, and redirect to Special:OpenIDConnectReturn on the wiki, which would validate the OpenID response and then redirect to the loginreturnurl provided in the first POST to the API with the code and state parameters added. The client gets control of the process back at this point and makes its next API request.

Step 2: Back from OpenID[edit]

Note: Now the client needs to ask the user to check their two-factor authentication app for the current code, and submit that back to the server to continue the authentication process.

Step 3: Two-factor authentication[edit]

Note: In certain cases it's possible to receive a RESTART response, for example if the OpenID Connect extension had no mapping for the OpenID account to any local user.In this case the client might restart the login process from the beginning or might switch to account creation, in either case passing the loginpreservestate or createpreservestate parameter to preserve some state.

Possible errors[edit]

Code Info
Failed Incorrect username or password entered. Please try again.
WrongToken Invalid token provided
NeedToken `lgtoken` not provided
Aborted login using the main account password rather than bot passwords

Additional notes[edit]

  • On wikis that allow anonymous editing, it's possible to edit through the API without logging in, but it's highly recommended that you do log in.On private wikis, logging in is required to use any API functionality.
  • It is recommended to create a separate user account for your application. This is especially important if your application is carrying out automated editing or invoking large or performance-intensive queries. With that, it is easy to track changes made by the application and apply special rights to the application's account.

See also[edit]

  • API:Userinfo - Returns information about the currently logged-in user