API:Login

From MediaWiki.org
Jump to navigation Jump to search
This page is a translated version of the page API:Login and the translation is 40% complete.
Other languages:
Deutsch • ‎English • ‎dansk • ‎español • ‎français • ‎italiano • ‎polski • ‎русский • ‎українська • ‎العربية • ‎فارسی • ‎ไทย • ‎中文 • ‎文言 • ‎日本語 • ‎한국어

MediaWiki API kann von Deiner Applikation oder Deinem Client verlangen, authentifizierte Benutzer-Credentials für (a) Query-Informationen oder datenmodifizierende Aktionen (b) die große Queries mit höheren Request-per-Limits vorzuweisen.

Zwei Methoden für die Authentifizierung

Es gibt zwei Wege, um sich bei der MediaWiki action API zu athentifizieren:

Methode 1. Login

Bot- und andere nichtinteraktive Applikationen sollten wenn verfügbar owner-only OAuth consumers verwenden, weil das sicherer ist. Wenn nicht verfügbar oder mit dem Client nicht anwendbar, kann die login-Action mit Botpasswörtern verwendet werden.

API-Dokumentation


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

Beispiel

POST request

lgtoken in the request above is retrieved from API:Tokens

Response

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

Sample code

Python

#!/usr/bin/python3

"""
    login.py

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

import requests

S = requests.Session()

URL = "https://www.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)

PHP

<?php

/*
    login.php

    MediaWiki API Demos
    Demo of `Login` module: Sending post request to login
    MIT license
*/

$endPoint = "https://test.wikipedia.org/w/api.php";

$login_Token = getLoginToken(); // Step 1
loginRequest( $login_Token ); // Step 2

// Step 1: GET request to fetch login token
function getLoginToken() {
	global $endPoint;

	$params1 = [
		"action" => "query",
		"meta" => "tokens",
		"type" => "login",
		"format" => "json"
	];

	$url = $endPoint . "?" . http_build_query( $params1 );

	$ch = curl_init( $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, "/tmp/cookie.txt" );
	curl_setopt( $ch, CURLOPT_COOKIEFILE, "/tmp/cookie.txt" );

	$output = curl_exec( $ch );
	curl_close( $ch );

	$result = json_decode( $output, true );
	return $result["query"]["tokens"]["logintoken"];
}

// Step 2: POST request to log in. Use of main account for login is not
// supported. Obtain credentials via Special:BotPasswords
// (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
function loginRequest( $logintoken ) {
	global $endPoint;

	$params2 = [
		"action" => "login",
		"lgname" => "your_bot_username",
		"lgpassword" => "your_bot_password",
		"lgtoken" => $logintoken,
		"format" => "json"
	];

	$ch = curl_init();

	curl_setopt( $ch, CURLOPT_URL, $endPoint );
	curl_setopt( $ch, CURLOPT_POST, true );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $params2 ) );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, "/tmp/cookie.txt" );
	curl_setopt( $ch, CURLOPT_COOKIEFILE, "/tmp/cookie.txt" );

	$output = curl_exec( $ch );
	curl_close( $ch );

	echo( $output );
}

JavaScript

/*  
    edit.js
 
    MediaWiki API Demos
    Demo of `Login` module: Sending post request to login

    MIT license
*/

var request = require('request').defaults({jar: true}),
    url = "https://test.wikipedia.org/w/api.php";

// Step 1: GET request to fetch login token
function getLoginToken() {
    var params_0 = {
        action: "query",
        meta: "tokens",
        type: "login",
        format: "json"
    };

    request.get({ url: url, qs: params_0 }, function (error, res, body) {
        if (error) {
            return;
        }
        var data = JSON.parse(body);
        loginRequest(data.query.tokens.logintoken);
    });
}

// Step 2: POST request to log in. 
// Use of main account for login is not
// supported. Obtain credentials via Special:BotPasswords
// (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
function loginRequest(login_token) {
    var params_1 = {
        action: "login",
        lgname: "bot_username",
        lgpassword: "bot_password",
        lgtoken: login_token,
        format: "json"
    };

    request.post({ url: url, form: params_1 }, function (error, res, body) {
        if (error) {
            return;
        }
        console.log(body);
    });
}

// Start From Step 1
getLoginToken();

MediaWiki JS

/*
	login.js
	MediaWiki API Demos
	Demo of `Login` module: Sending request to login
	MIT License
*/

var api = new mw.Api();

api.login( 'your_bot_username', 'your_bot_password' ).done( function ( data ) {
	console.log( 'You are logged in as ' + data.login.lgusername );
} );
As of MediaWiki 1.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

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 1.27.

API documentation


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

POST request

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

Response

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

Sample code

Example 2: Process for a wiki with special authentication extensions

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

Vom Client wird erwartet, den Browser des Benutzers zum bereitgestellten redirecttarget weiterzuleiten. Der OpenID-Anbieter sollte authentifizieren und zu Special:OpenIDConnectReturn im Wiki weiterleiten, was die OpenID-Antwort validieren würde und dann weiterleiten zur loginreturnurl, die im ersten POST an die API bereitgestellt wurde, mit angehängten code- und state-Parametern. Der Client erhält an diesem Punkt die Konktrolle über den Prozess zurück und macht seine nächste API-Anfrage.

Step 2: Back from OpenID

Nun muss der Client die Benutzer bitten, ihre Zwei-Faktor-Authentifizierungs-App für den aktuellen Code zu prüfen und dies zurück an den Server zu übermitteln, um den Authentifizierungsprozess fortzusetzen.

Step 3: Two-factor authentication

Beachte: In bestimmten Fällen ist es möglich, eineRESTART-Antwort zu erhalten, zum Beispiel, wenn die OpenID Connect-Erweiterung kein Mappung für den OpenID-Account eines lokalen Benutzers findet. In diesem Fall kann der Client dien Loginprozess ganz von vorn neustarten oder zur Accounterstellung wechseln wollen. In beiden Fällen gibt er den loginpreservestate- oder den createpreservestate-Parameter mit, um einige Status zu erhalten.

Possible errors

Code Info
Failed Falscher Benutzername oder falsches Passwort eingegeben. Bitte erneut versuchen.
WrongToken Fehlerhaftes Token übergeben
NeedToken `lgtoken` not provided
Aborted Login besser mit dem Hauptpasswort statt mit beiden Passwörtern
mustpostparams The following parameters were found in the query string, but must be in the POST body: $1.

Zusätzliche Anmerkungen

  • In Wikis, die anonymes Bearbeiten erlauben ist möglich, mit der API zu bearbeiten, ohne sich einzuloggen, aber es ist sehr empfehlenswert, dass Du dich einloggst. In privaten Wikis ist das Einloggen für jeder API-Funktinalität erforderlich.
  • 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.
  • If you are sending a request that should be made by a logged-in user, add assert=user parameter to the request you are sending in order to check whether the user is logged in. If the user is not logged-in, an assertuserfailed error code will be returned.
  • To check if an account has bot rights, add assert=bot parameter to the request. If the account does not have bot rights, an assertbotfailed error code will be returned.

Siehe auch

  • API:Userinfo - Gibt Informationen über den aktuell eingeloggten Benutzer zurück