واجهة برمجة التطبيقات:تسجيل_الدخول

From mediawiki.org
This page is a translated version of the page API:Login and the translation is 100% complete.

ربما تتطلب واجهة برمجة تطبيقات ميدياويكي من تطبيقك أو جهازك العميل تقديم بيانات اعتماد مستخدم مصدّقة وتسجيل الدخول لأغراض (أ) الاستعلام عن معلومات أو تصرفات تعدّل بيانات أو (ب) إجراء استعلامات ضخمة الحجم ينتج عنها طلبات تتخطى الحد الأقصى.

استخدام سبيلين اثنين للتصديق

يوجد سبيلين اثنين للتصديق على واجهة برمجة التطبيقات لتطبيق Action على ميدياويكي: باستخدام action=login أو action=clientlogin.

الطريقة الأولى: action=login

يجب على البوتات والتطبيقات غير التفاعلية استخدام مستهلكي OAuth من الملاك فقط لو كان ذلك متوفرا منذ انه يتمتع بأمان أكبر. لو كان هذا غير متوافر أو لا ينطبق على الجهاز العميل، يجوز استخدام login مع كلمات مرور البوتات.

توثيق واجهة برمجة التطبيقات


action=login (lg)

(main | login)
  • This module requires write rights.
  • 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.

Specific parameters:
Other general parameters are available.
lgname

Username.

lgpassword

Password.

lgdomain

Domain (optional).

lgtoken

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

مثال

طلب POST


lgtoken الموجود في الطلب المذكور سالفا يرجع من واجهة برمجة التطبيقات:Tokens

النتيجة

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

عينة من الكود البرمجي

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 );
} );

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 = {
		action: 'query',
		meta: 'tokens',
		type: 'login',
		format: 'json'
	};

	request.get( { url: url, qs: params }, function ( error, res, body ) {
		var data;
		if ( error ) {
			return;
		}
		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( loginToken ) {
	var params = {
		action: 'login',
		lgname: 'bot_username',
		lgpassword: 'bot_password',
		lgtoken: loginToken,
		format: 'json'
	};

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

// Start From Step 1
getLoginToken();

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 );
}

Python

#!/usr/bin/python3

"""
    login.py

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

import requests

USERNAME = "your_bot_username"
PASSWORD = "your_bot_password"

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': USERNAME,
    'lgpassword': PASSWORD,
    'lgtoken': LOGIN_TOKEN,
    'format': "json"
}

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

print(DATA)
assert DATA['login']['result'] == 'Success'
بدءًا من إصدار ميدياويكي 1.27، لم يعد مدعومًا استخدام الحساب الرئيسي لتسجيل الدخول. أحصل على بيانات الاعتماد مستخدمًا Special:BotPasswords أو استخدم طريقة clientlogin. يتطلب تسجيل الدخول وأن تظل مسجلًا الدخول التعامل الصحيح من ملفات تعريف ارتباط إتش تي تي بي على يد جهازك العميل فيما يخص كافة الطلبات. في المثال سالف الذكر، نبين كيف يساعد عنصر الجلسة requests.Session() في إبقاء ملفات تعريف الارتباط.

الأخطاء المحتملة

الكود معلومات
Failed اسم مستخدم أو كلمة مرور خطأ. يرجى المحاولة مرة أخرى.
Failed لا يمكن مواصلة تسجيل الدخول. يغلب الظن أن جلستك قد انتهى زمنها. (أو أنك لست تتعامل مع ملفات تعريف الارتباط كما ينبغي).
WrongToken الرمز المقدم غير صالح
NeedToken رمز `lgtoken` لم يقدم
Aborted تسجيل الدخول مستخدما كلمة مرور الحساب الرئيسي بدلا من كلمات مرور البوتات
mustpostparams تم العثور على الوسيط في سلسلة الاستعلام، ولكن يجب أن يكون في نص POST: $1.

الطريقة الثانية: action=clientlogin

يجب أن تستخدم التطبيقات التفاعلية من قبيل المحررات المخصصة أو تطبيقات المراجعة التي تقدم خدمة ليس الغرض منها أن تكون بديلا كاملا عن الموقع الشبكي أو تطبيقات الأجهزة المحمولة التي تستهدف أن تحل بالكامل محل الوصول إلى واجهة المستخدم عبر الوب تصرف clientlogin. إلا أن على المرء أن يفضل استخدام OAuth لو كان متوفرًا لأغراض تصديق الأداة ذاتها، منذ أنه أيسر في الاستخدام وآمن كذلك. هذه الوحدة البرمجية متوفرة منذ إصدار ميدياويكي 1.27.

توثيق واجهة برمجة التطبيقات


action=clientlogin (login)

(main | clientlogin)
  • This module requires write rights.
  • 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.
Specific parameters:
Other general parameters are available.
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 clients that are allowed higher limits).
loginmessageformat

Format to use for returning messages.

One of the following values: html, none, raw, wikitext
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]

مثال 21: عملية لموقع ويكي لا يحتوي على امتدادات تصديق خاصة

طلب POST


الحصول على رمز تسجيل الدخول في الطلب سالف الذكر مستخدمًا واجهة برمجة التطبيقات:Tokens .

النتيجة

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

عينة من الكود البرمجي

clientlogin.py
#!/usr/bin/python3

"""
    clientlogin.py

    MediaWiki Action API Code Samples
    Demo of `clientlogin` module: Sending post request to login

    This demo app uses Flask (a Python web development framework).

    MIT license
"""

import requests
from flask import Flask, render_template, flash, request

S = requests.Session()
URL = "https://en.wikipedia.org/w/api.php"

# App config.
DEBUG = True
APP = Flask(__name__)
APP.config.from_object(__name__)
APP.config['SECRET_KEY'] = 'enter_your_secret_key'


@APP.route("/", methods=['GET', 'POST'])
def show_form():
    """ Render form template and handle form submission request """

    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        start_client_login(username, password)

    return render_template('clientlogin_form.html')

def start_client_login(username, password):
    """ Send a post request along with login token, user information
    and return URL to the API to log in on a wiki """

    login_token = fetch_login_token()

    response = S.post(url=URL, data={
        'action': "clientlogin",
        'username': username,
        'password': password,
        'loginreturnurl': 'http://127.0.0.1:5000/',
        'logintoken': login_token,
        'format': "json"
    })

    data = response.json()

    if data['clientlogin']['status'] == 'PASS':
        flash('Login success! Welcome, ' + data['clientlogin']['username'] + '!')
    else:
        flash('Oops! Something went wrong -- ' + data['clientlogin']['messagecode'])

def fetch_login_token():
    """ Fetch login token via `tokens` module """

    response = S.get(
        url=URL,
        params={
            'action': "query",
            'meta': "tokens",
            'type': "login",
            'format': "json"})
    data = response.json()
    return data['query']['tokens']['logintoken']

if __name__ == "__main__":
    APP.run()
form.html
<!DOCTYPE html>
  <title>MediaWiki Log in</title>
  <link rel="stylesheet" href="static/bootstrap/css/bootstrap.min.css">

<div class="container">
  <h2>MediaWiki Log in</h2>
  <form action="" method="post" role="form">
    <div class="form-group">
      <div class="form-field">
        <div class="label-field">Username</div>
        <input name="username">
      </div>
      <div class="form-field">
        <div class="label-field">Password</div>
        <input type="password" name="password">
      </div>
    </div>
    <button type="submit" class="btn btn-success">Log in</button>
  </form>
  <br>
  {% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
  {% for message in messages %}
  <div class="alert alert-info">
    {{ message[1] }}
  </div>
  {% endfor %}
  {% endif %}
  {% endwith %}
</div>
<br>
</div>
</div>

مثال 22: عملية لموقع ويكي يحتوي على امتدادات تصديق خاصة

قد يكون الأمر لموقع ويكي يحتوي على امتدادات تصديق خاصة مثل امتداد:تأكيد التعديل (كابتشا) أو OpenID Connect أو OATHAuth (التصديق باستخدام عنصرين اثنين) عملية تصديق أكثر تعقيدًا. كما قد يتطلب الأمر خانات محددة في تلك الحالة، ويمكن استجلاب بيان هذه من استعلام API:Authmanagerinfo .

الخطوة الأولى: الإجابة على Captcha واختيار تصديق OpenID

أعمال التوثيق هذه مثال لا غير ولا تعرض سلوك أية امتدادات OpenID محددة متاحة حاليًا.


نتوقع من الجهاز العميل إعادة توجيه متصفح المستخدم إلى صفحة redirecttarget المحددة. سيتولى مقدم خدمة OpenID التصديق ومن ثم إعادة التوجيه إلى صفحة Special:OpenIDConnectReturn على موقع الويكي، التي سوف تتولى التثبت من رد OpenID ومن ثم إعادة التوجيه إلى loginreturnurl شريطة أن تضاف المتغيرات code و state إلى طلب POST الأول المقدم إلى واجهة برمجة التطبيقات. ستنتقل السيطرة على العملية إلى جهاز العميل مرة أخرى عند هذه الخطوة ومن ثم يرسل طلب واجهة برمجة التطبيقات التالي.
الرد
{
    "clientlogin": {
        "status": "REDIRECT",
        "redirecttarget": "https://openid.example.net/openid-auth.php?scope=openid&response_type=code&client_id=ABC&redirect_uri=https://wiki.example.org/wiki/Special:OpenIDConnectReturn&state=XYZ123",
        "requests": [
            {
                "id": "OpenIdConnectResponseAuthenticationRequest",
                "metadata": {},
                "required": "required",
                "provider": "OpenID Connect at example.net",
                "account": "",
                "fields": {
                    "code": {
                        "type": "string",
                        "label": "OpenID Code",
                        "help": "OpenID Connect code response"
                    },
                    "state": {
                        "type": "string",
                        "label": "OpenID State",
                        "help": "OpenID Connect state response"
                    },
                }
            }
        ]
    }
}
الآن يحتاج الجهاز العميل أن يطلب من المستخدم التحقق من تطبيق التصديق باستخدام عنصرين اثنين بحثًا عن الكود الحالي ومن ثم تمريره مرة أخرى إلى الخادوم من أجل مواصلة عملية التصديق.
الرد
{
    "clientlogin": {
        "status": "UI",
        "message": "Two-factor authentication",
        "requests": [
            {
                "id": "TwoFactorAuthenticationRequest",
                "metadata": {},
                "required": "required",
                "provider": "",
                "account": "",
                "fields": {
                    "code": {
                        "type": "string",
                        "label": "Code",
                        "help": "Two-factor authentication code"
                    }
                }
            }
        ]
    }
}
من الممكن في بعض الحالات المعينة تلقي رد RESTART، على سبيل المثال لو كان امتداد OpenID Connect لم يكن يحتوي على ربط لحساب OpenID مرتبط بحساب مستخدم محلي. في هذه الحالة يجوز أن يعيد الجهاز العميل تشغيل عملية تسجيل الدخول من بدايتها أو يجوز أن ينتقل إلى إنشاء حساب، في كلتا الحالتين سيمرر المعامل loginpreservestate أو createpreservestate كي يحافظ على بعض الحالة.
الرد
{
    "clientlogin": {
        "status": "PASS",
        "username": "Alice"
    }
}

ملاحظات إضافية

  • من الممكن على مواقع الويكي التي تسمح بالتعديل دون تسجيل دخول تعديل واجهة برمجة التطبيقات دون تسجيل الدخول، إلا أننا ننصح بشدة أن تسجل الدخول. فيما يخص مواقع الويكي الخصوصية، يتطلب الأمر تسجيل الدخول كي تستخدم أي من وظائف واجهة برمجة التطبيقات.
  • نحبّذ إنشاء حساب مستخدم لتطبيقك. هذا الأمر مهم على وجه التحديد لو كان تطبيقك ينفذ أعمال تعديل مؤتمتة أو يستدعي استفسارات ضخمة أو تتطلب مقدار كبير من المعالجة. بالنظر إلى ذلك، يسهل متابعة التغييرات التي أجراها التطبيق وإسباغ حقوق خاصة للحساب الذي يستخدمه التطبيق.
  • لو كنت ترسل طلب يجب أن يرسله مستخدم مسجل الدخول، أضف المتغير assert=user إلى الطلب الذي ترسله كي تتحقق من أن المستخدم مسجل الدخول أم لا. لو كان المستخدم غير مسجل الدخول، سوف يرد الطلب كود الخطأ assertuserfailed إليك. طالع واجهة برمجة التطبيقات:أكّد لترى التفاصيل.
  • لو كنت تريد أن تتحقق من أن حساب ما يتمتع بحقوق بوت، أضف المتغير assert=bot إلى الطلب. لو كان الحساب لا يتمتع بحقوق بوت، سوف يرد الطلب كود الخطأ assertbotfailed إليك. طالع واجهة برمجة التطبيقات:أكّد لترى التفاصيل.

انظر أيضا