OAuth/Для разработчиков

From MediaWiki.org
Jump to navigation Jump to search
This page is a translated version of the page OAuth/For Developers and the translation is 97% complete.

Other languages:
English • ‎Esperanto • ‎русский • ‎日本語

На этой странице объясняется, как разрабатывать приложения, которые могут интегрироваться с вики с запущенным Extension:OAuth (расширение, превращающее MediaWiki в сервер OAuth) для безопасного запроса разрешения действовать от имени пользователя.

Если вы разрабатываете бота или подобное приложение, в котором один и тот же потребитель всегда используется с одной и той же учетной записью пользователя, вы можете предпочесть более простые только для владельцев (owner-only consumers).

OAuth в двух словах

OAuth позволяет приложению запрашивать разрешение у пользователя действовать через его вики-учетную запись, не зная пароля пользователя, и при этом не в состоянии делать все, что может пользователь (например, приложение может редактировать статьи, но не удалять их, поэтому даже пользователи с расширенными разрешениями могут безопасно использовать инструменты с поддержкой OAuth).

Это происходит по протоколу OAuth 1.0a и состоит из трех компонентов:

  1. Разработчик должен зарегистрировать приложение (часто называемое «потребителем» в терминологии OAuth) в вики, возможно, пройти через процесс проверки и получить определённые учетные данные.
  2. Когда пользователь хочет использовать его, приложение должно инициировать процесс авторизации. Это будет включать отправку пользователя на специальную страницу в вики, где будет отображаться диалог авторизации. Если пользователь подтверждает авторизацию, приложение получит другой набор учетных данных (которые относятся к этому пользователю и могут быть отозваны пользователем в любое время).
  3. Когда приложению действительно необходимо выполнить действие (запрос API) от имени пользователя, оно может объединить учетные данные, полученные на этапах 1 и 2, для подписания запроса.

OAuth - это широко используемый открытый стандарт (вы можете увидеть его на таких сайтах, как Google, Facebook или GitHub, например, при использовании учетных записей на этих сайтах для входа в систему в другом месте). Его не следует путать с OATH (проверке при двух-факторной аутентификации, обычно известным как «введите шесть цифр, которые вы видите в своем мобильном приложении», теперь включенным на сайтах Викимедиа) и OpenID Connect (протокол аутентификации на основе OAuth 2.0 - расширение OAuth MediaWiki включает в себя несколько похожий на OpenID пользовательский протокол для определения личности пользователя).

Для больших подробностей смотрите эту презентацию

OAuth деталях

Регистрация

To register a new OAuth application, submit the form at Special:OAuthConsumerRegistration/propose. Try to give sufficient information about the application for admins and users to decide whether it can be trusted. URLs to places with more information (such as the application itself, the source code or on-wiki documentation) can be useful. For OAuth applications to be used on Wikimedia projects, see app guidelines.

Besides the descriptive ones, the fields have the following meaning:

  • This consumer is for use only by <user>: for owner-only consumers (which do not need to be reviewed or authorized but are only usable by yourself)
  • callback URL: the URL where the user return after authorization is checked against this. (This is an extra layer of security against an attacker trying to steal credentials during authorization.) If the "use as prefix" option is enabled, the URL must start with this (the check is dumb so make sure to add at least a / after the domain name), otherwise it must be an exact match. If you are developing/testing your local machine, specify Localhost in this field (e.g. http://localhost:8080/).
  • Applicable project (for wiki farms only): you can limit the application to a single wiki or have it work everywhere.
  • Types of grants / Applicable grants: the permissions needed by your application (be conservative). The actual permissions will be an intersection of this and what permissions the user has. At this time, the user must authorize all permissions together (T59505).
  • Allowed IP ranges: OAuth requests not matching this will be rejected. (This is an optional extra layer of security against an attacker stealing your application's credentials and trying to impersonate it.) One of the few settings that you'll be able to change later.
  • Public RSA key: public key used by your application for signing requests. You can just leave this empty (most applications do) to use a slightly simpler shared-secret mechanism instead. One of the few settings that you'll be able to change later. After registration, you'll receive the credentials needed to use OAuth. You will be able to use it immediately with your own user account (this is meant for testing); others will only be able to use it once it is approved by an administrator.

If you have changed your mind, you can disable the application under Special:OAuthConsumerRegistration/list. The list of applications (approved or otherwise) is public and can be browsed at Special:OAuthListConsumers.

Авторизация

Authorization dialog shown to users

When registering the application, you receive two pieces of credentials: the application token (a public ID for the application) and the application secret (sort of like a password). To be able to identify a user or make API requests in their name, you need to get another set of credentials (these ones specific to that user): the access token and access secret.[1] To get them, you need to go through the authorization process, which consists of three steps:[2]

  1. Get a request token from the wiki by sending a GET request to Special:OAuth/initiate,[3] signed with the application key and secret, with the callback URL (where the user will be sent after a successful authorization) passed as the oauth_callback query parameter (if you have set a constant URL at registration, the value of the parameter must be oob). If you are successful, the response will be a JSON object with token and key fields - the request token and request secret. (If not, it will have an error field.)
  2. Ask the user to authorize the application by sending them to Special:OAuth/authorize,[4] with the application token and request token passed as query parameters (oauth_consumer_key and oauth_token, respectively). The user will see an authorization dialog with some basic information about the application and the list of grants, and can decide to authorize or cancel.
  3. If the user did choose to authorize, they will be redirected to the callback URL you have given (at registration, or as an URL parameter in step 1). A query parameter called oauth_verifier will contain the verification code that you can use to exchange the request token and secret for the access token and secret. To do this, send a request to Special:OAuth/token[3] which includes the oauth_verifier parameter you just received and is signed with the application token and secret and the request token and secret. The response will contain the access token/secret (in the same format as the request token/secret in step 1).

The access token and secret is what you'll need to sign API requests. The request token and secret is not useful anymore and can be discarded. The access token will remain valid indefinitely, unless the user revokes it. (If you prefer not to store it, you can just repeat the authorization process at any time though.)

Applications which only need minimal privileges (have been registered as User identity verification only) can use /authenticate instead of /authorize in step 2. This works the same way but the user will only see the authorization dialog if they have not authorized this application before; otherwise the authorization will silently succeed.

Chances are whatever language/framework you are using will have a library to support this procedure so you don't have to implement it manually - each step will be a single function call. See below for examples.

Создание запросов от имени пользователя

To take advantage of the authorization, requests have to be signed with the application token/secret and access token/secret. When that's successfully done, the wiki will treat the request as if it was made by the authorizing user. Only API requests can be made via OAuth, with one exception (see next section). Certain API modules which would not make sense with OAuth (such as login/logout) or would allow privilege escalation (such as the centralauthtoken API) are disabled.

Applications which need minimal privileges (have been registered as User identity verification only) cannot use the API at all.

Идентификация пользователя

The OAuth extension includes a custom protocol (similar to OpenID Connect) for authenticating the user. To use this, send a signed OAuth request to Special:OAuth/identify;[3] the response will be a JWT (a signed JSON object) including the name of the user, their central ID (under the key sub) and various other information (such as their user groups and whether they are blocked; also the email address if the application was registered with the right grant type). This is more secure than using the API (e.g. the userinfo module) for authentication, which could be subject to man-in-the-middle attacks; always use this if you need to identify a user! Also, make sure you properly validate the JWT (there are many libraries which can help with that). You should check each of the following: the issuer (iss) matches the domain name of the wiki, the audience (aud) matches your application key, the issued-at time (iat) is in the past and reasonably close to current time, the expiration time (exp) is in the future, the nonce (nonce) matches the one you sent in the request.


Подписывание запросов

Steps 1 and 3 of the authorization process require signing the request; API requests and Special:OAuth/identify must likewise be signed. The signing process is detailed in section 9 of the OAuth spec, but it is cumbersome to do implement by hand and many libraries are available. You can find code samples and an overview of how to do it by hand in the owner-only consumer documentation. (That is for signing with the consumer token/secret and access token/secret. Modify as appropriate to sign with the consumer token/secret and request token/secret (authorization step 3) or consumer token/secret only (authorization step 1)

Настройка среды разработки

OAuth is now available in your MediaWiki-Vagrant development environment. Add the oauth role, and your wiki will be able to authorize OAuth apps.

$ vagrant roles enable oauth
$ vagrant provision

Alternatively, you can register an OAuth application on beta meta and test your code against that.

Once the code is nearly ready, you can register an OAuth application on the real wiki. You will be able to test it with the same user account used for registering, even before it gets reviewed by admins.

If you are creating an application for Wikimedia projects, consider hosting it at Wikimedia Tools, a free tool forge and hosting platform for Wikimedia-related services.

Преимущества безопасности и компромиссы

  • Unlike password-based authentication, the protocol prevents any man-in-the-middle attack even if the wiki does not require HTTPS: all interactions between MediaWiki and the application are signed with either a shared secret (using HMAC-SHA1), or a public key (RSA). HTTPS is still required for certain steps though (for obtaining the shared secret in the second step of authorization when not using RSA, and during app registration).
  • Actions via OAuth happen under the user's name but will be tagged with the application's name as well so rogue applications can be identified. Wiki admins can revoke the application's permissions (and thus bar it from any further action) if needed.
  • The user can revoke the permission of the application to use that specific user account if they don't like how it works or don't trust it anymore. Unlike a password change, this is not disruptive for the user.
  • Sufficiently flexible applications might allow users to circumvent IP blocks (since MediaWiki will see the IP of the application server, not that of the user). This can be handled the same way proxies are, by trusting XFF headers set by the application (see T159889 for some limitations).
  • The application secret must be kept secret. Submitting it to source control or putting it into user-accessible code (such as mobile app or desktop application; even if it is obfuscated) undermines the security model and will result in admins forcefully disabling the application. Exceptions are made for example applications demoing OAuth usage, if they are explicitly labeled as such and request limited rights.

Библиотеки

PHP

Python

Ruby

Node.js

  • passport-mediawiki-oauth - MediaWiki strategy for the Passport auth framework (which can be used effortlessly as a middleware with Express JS and similar frameworks)
  • oauth-fetch-json - library for signing OAuth requests

Go

Java

Примеры кода

PHP-клиент без использования библиотек

OAuth Hello World – easy to understand demo application written in PHP without any libraries.

PHP command-line client with RSA keys, using oauthclient-php

PHP application using classes from the OAuth extension codebase. (TODO convert this to actually use oauthclient-php! Probably just a bunch of use declarations.)

Before Starting:

$ openssl genrsa -out appkey.pem 4096
$ openssl rsa -in appkey.pem -pubout > appkey.pub

Клиент Python для командной строки, использующий mwoauth

Python Toolforge tutorial using mwoauth

Смотрите: wikitech:Help:Toolforge/My first Flask OAuth tool

Go клиент командной строки, используя mrjones /lauth

Прежде чем вы начнете:

$ go get github.com/mrjones/oauth

Полные приложения, использующие OAuth

Заметки

  1. With an RSA key the credentials are slightly different. It is assumed that people choosing to use an RSA key know what they are doing, so this tutorial will assume you have chosen the non-RSA option.
  2. This is sometimes called three-legged OAuth flow. In certain circumstances a simpler, one-step alternative (one-legged OAuth) is also available. See owner-only consumers for that.
  3. 3.0 3.1 3.2 Due to a bug you must currently use a non-nice URL such as en.wikipedia.org/w/index.php?title=Special:OAuth/initiate.
  4. Due to another bug you must use a nice URL here, such as en.wikipedia.org/wiki/Special:OAuth/authorize. A bit embarrassing, we know.