Расширение:OAuth

From mediawiki.org
This page is a translated version of the page Extension:OAuth and the translation is 42% complete.
Outdated translations are marked like this.
Not to be confused with Extension:OATHAuth or Extension:WSOAuth.
Справка по расширениям MediaWiki
OAuth
Статус релиза: стабильно
Реализация Идентификация пользователя , Права пользователя , API
Описание Позволяет пользователям безопасно разрешать другому приложению («потребителю») использовать API действий MediaWiki от их имени.
Автор(ы) Aaron Schulz, Chris Steipp, Brad Jorsch, Robert Vogel, Dejan Savuljesku
Последняя версия 1.1.0 (continuous updates)
Политика совместимости Snapshots releases along with MediaWiki. Master is not backward compatible.
MediaWiki >= 1.42
Изменения в БД Да
Composer mediawiki/oauth
Таблицы oauth_accepted_consumer
oauth_registered_consumer
Лицензия GNU General Public License 2.0 или позднее
Скачать
Помощь Справка:OAuth
  • $wgOAuth2PublicKey
  • $wgOAuth2RequireCodeChallengeForPublicClients
  • $wgMWOAuthCentralWiki
  • $wgMWOAuthSecureTokenTransfer
  • $wgMWOAuthSharedUserSource
  • $wgOAuth2GrantExpirationInterval
  • $wgOAuthAutoApprove
  • $wgMWOauthDisabledApiModules
  • $wgOAuth2EnabledGrantTypes
  • $wgMWOAuthNonceCacheType
  • $wgOAuthGroupsToNotify
  • $wgMWOAuthRequestExpirationAge
  • $wgOAuth2RefreshTokenTTL
  • $wgMWOAuthSessionCacheType
  • $wgMWOAuthReadOnly
  • $wgOAuth2PrivateKey
  • $wgMWOAuthSharedUserIDs
  • $wgOAuthSecretKey

  • mwoauthproposeconsumer
  • mwoauthupdateownconsumer
  • mwoauthmanageconsumer
  • mwoauthsuppress
  • mwoauthviewsuppressed
  • mwoauthviewprivate
  • mwoauthmanagemygrants
Ежеквартальные загрузки 91 (Ranked 67th)
Использование общедоступными вики 982 (Ranked 246th)
Переведите расширение OAuth, если оно доступно на translatewiki.net
Роль Vagrant oauth
Проблемы Открытые задачи · Сообщить об ошибке

Расширение OAuth реализует сервер OAuth в MediaWiki, который поддерживает версии протокола OAuth 1.0a и OAuth 2.0. Это позволяет сторонним разработчикам безопасно разрабатывать приложения («потребителей»), которым пользователи могут предоставлять ограниченный набор разрешений («гранты»), чтобы приложение могло использовать API действий MediaWiki от имени пользователя.

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

Требования

  • OAuth использует кеш объектов для временных токенов и сеансов. Это должно работать до тех пор, пока параметры конфигурации кэша в порядке. (Older versions required Memcached explicitly.)
  • В настоящее время поддерживаются только серверные части баз данных MySQL и SQLite.
  • Если установка MediaWiki является закрытой (т. е. пользователям необходимо войти в систему, чтобы получить доступ для чтения), Special:OAuth нужно будет добавить в белый список.

Установка


Установка Vagrant:

  • Если вы используете Vagrant , установите с помощью vagrant roles enable oauth --provision

Чтобы назначить разрешение какой-либо группе, например системным операторам, вы добавляете следующую строку в LocalSettings.php:

$wgGroupPermissions['sysop']['mwoauthproposeconsumer'] = true;

Настройка

Parameters

Название переменной Значение по умолчанию Описание
$wgMWOAuthCentralWiki false Wiki ID для управления вики через OAuth. Имеет смысл установить это значение для вики, которая действует как сайт-портал, предназначенный для управления или просто обрабатывает вход/аутентификацию. Тем не менее, его можно установить для любой вики в отдельности. Для сайтов с одной вики или группы, где каждая вики управляет "потребителями" отдельно, следует оставить значение false.
$wgMWOAuthSharedUserIDs false (устарело) Используйте $wgMWOAuthSharedUserSource вместо этого

Который сохраняет общие глобальные идентификаторы пользователей в таблицах OAuth. На вики кластерах с центральной системой аутентификации (с целочисленными идентификаторами пользователей), которые совместно используют одну вики управления OAuth, для этого параметра должно быть установлено значение true. Если у вики есть центральная система аутентификации, но собственное управление OAuth, то этот параметр может быть либо true, либо false. В противном случае он всегда должен быть установлен на false. Если для этого параметра установлено значение true, требуется CentralIdLookup или расширение аутентификации с поддержкой MWOAuth. Это значение не следует изменять задним числом, чтобы избежать неоднозначных идентификаторов. Перед любыми такими изменениями необходимо выполнить правильную миграцию идентификатора пользователя.

$wgMWOAuthSharedUserSource null Поставщик центральной идентификации при совместном использовании учетных данных OAuth через вики-кластер

Источник общих идентификаторов пользователей, если он включен. Если доступен CentralIdLookup, это $providerId для CentralIdLookup::factory(). Как правило, нуль/null, если вы хотите, чтобы использовать поставщика услуг индентификации по умолчанию. Если этот класс недоступен или именованный провайдер не найден, то передается в OAuthGetUserNamesFromCentralIds, OAuthGetLocalUserFromCentralId, OAuthGetCentralIdFromLocalUser, OAuthGetCentralIdFromUserName. Это не действует, если для $wgMWOAuthSharedUserIDs установлено значение false.

$wgMWOAuthRequestExpirationAge 2 592 000 (30 days) Секунды, после которых бездействующий запрос нового потребителя помечается как «истекший».
$wgMWOAuthSecureTokenTransfer true Требовать SSL/TLS для возврата потребительских и пользовательских секретны кодов. Это требуется для RFC 5849, однако, если вики хочет использовать OAuth, но не поддерживает SSL, эта опция делает эту настройку возможной. This should be set to true for most production settings.
$wgOAuthSecretKey $wgSecretKey A secret configuration string (random 32-bit string generated using "base64_encode(random_bytes(32))") used to hmac the database-stored secret to produce the shared secrets for Consumers. This provides some protection against an attacker reading the values out of the consumer table (the attacker would also need $wgOAuthSecretKey to generate valid secrets), and some protection against potential weaknesses in the secret generation. If this string is compromised, the site should generate a new $wgOAuthSecretKey, which will invalidate Consumer authorizations that use HMAC/shared secret signatures instead of public/private keys. Consumers can regenerate their new shared secret by using the "Reset the secret key to a new value" option under Special:MWOAuthConsumerRegistration/update. If null, the value is set to $wgSecretKey.
$wgOAuthGroupsToNotify [] The list of user groups which should be notified about new consumer proposals. Setting this will only have an effect when Echo is installed.
$wgMWOauthDisabledApiModules [] List of API module classes to disable when OAuth is used for the request
$wgMWOAuthReadOnly false Prevent write activity to the database. When this is set, consumers cannot be added or updated, and new authorizations are prohibited. Authorization headers for existing authorizations will continue to work. Useful for migrating database tables
$wgMWOAuthSessionCacheType $wgSessionCacheType The storage mechanism for session data. If null, it defaults to $wgSessionCacheType.
$wgOAuthAutoApprove [] Allows automatic immediate approval of low-risk apps. In the form of [ 'grants' => [ 'grant1', 'grant2', ... ] ]
$wgOAuth2EnabledGrantTypes
[
"authorization_code",
"refresh_token",
"client_credentials"
]
List of OAuth2 grants that client applications can be allowed to use. Actual grants client application will be allowed to use can be any subset of grants listed here. Grants, other than the ones listed here, are considered legacy grants, and are not supported by this extension
$wgOAuth2PrivateKey "" Private key or a path to the private key used to sign OAuth2 JWT being transmitted. See the OAuth 2.0 Server documentation for how to generate the keys.
$wgOAuth2PublicKey "" Public key or a path to the public key used to verify OAuth2 resource requests.
$wgOAuth2RequireCodeChallengeForPublicClients true Controls whether clients are required to send code challenges with OAuth2 requests. This only applies to non-confidential clients.
$wgOAuth2GrantExpirationInterval "PT1H" (1 hour) Controls validity period for access tokens (stored in the cache configured in MWOAuthSessionCacheType). Does not apply to owner-only clients, whose access tokens are always non-expiring. Accepts ISO 8601 durations or can be set to "infinity" or false for non-expiring tokens.
$wgOAuth2RefreshTokenTTL "P1M" (1 month) Controls validity period for refresh tokens (stored in the cache configured in MWOAuthSessionCacheType). Accepts ISO 8601 durations or can be set to "infinity" or false for non-expiring tokens.

Права участников

Право Описание
mwoauthproposeconsumer Предложение новых клиентов OAuth
mwoauthupdateownconsumer Обновление контролируемых клиентов OAuth
mwoauthmanageconsumer Управление клиентами OAuth
mwoauthsuppress Сокрытие клиентов OAuth
mwoauthviewsuppressed Просмотр скрытых клиентов OAuth
mwoauthviewprivate Просмотр персональных данных OAuth
mwoauthmanagemygrants Управление разрешениями OAuth

Endpoints

OAuth 2.0 REST endpoints

The following REST endpoints are provided for OAuth 2.0 interaction

Path Описание Допустимые параметры Допустимый метод
/oauth2/authorize Used for retrieving authorization code when using authorization_code grant.
Название Требуется? Описание
response_type Да
client_id Да
redirect_uri Нет if present, must match the URI that was set when client was registered exactly
scope Нет
state Нет
code_challenge Нет required if $wgOAuth2RequireCodeChallengeForPublicClients is true
code_challenge_method Нет required if $wgOAuth2RequireCodeChallengeForPublicClients is true
GET
/oauth2/access_token Used for requesting access tokens
Название Требуется? Описание
grant_type Да type of grant used
client_id Нет
client_secret Нет required if client is confidential
redirect_uri Нет if present, must match the URI that was set when client was registered exactly
scope Нет
code Нет required if authorization_code grant is used
refresh_token Нет required if refresh_token grant is used
code_verifier Нет
POST
/oauth2/resource/{{type}} Used for retrieving protected resources using the access token issued previously.

Currently, two resource types can be retrieved using this endpoint, by replacing {{type}} placeholder with the type key:

  • profile - retrieve the user profile of the user that is represented by the access token used to make the request - usually used for logging users in on 3rd party websites using MediaWiki
  • scopes - retrieve all scopes client (application) is allowed to use with the current access token
No parameters are allowed, apart from the {{type}} parameter that is included in the path GET/POST
/oauth2/client Lists OAuth 1.0a or 2.0 clients for the logged-in user. Authentication can be achieved over CentralAuth or by including an access token in the authorization header.
Response example
{
  "clients": [
    {
      "client_key": "xxxxxxxxxxxxxx",
      "name": "TestFromCurl1807",
      "version": "2.0",
      "email": "admin@example.com",
      "callback_url": "http://example.com",
      "scopes": [
        "authonly"
      ],
      "registration": "20200818230806",
      "stage": 0,
      "oauth_version": 2,
      "description": "foo",
      "allowed_grants": [
        "authorization_code"
      ],
      "registration_formatted": "23:08, 18 August 2020"
    }
  ],
  "total": 1
}
  • oauth_version (optional) - either 1 (to return only OAuth 1.0a clients) or 2 (to return only OAuth 2.0 clients). По умолчанию: 2
  • Pagination parameters
    • limit (optional) - maximum number of clients to return. По умолчанию: 25
    • offset (optional) - number of clients to skip before returning the first result. По умолчанию: 0
GET
/oauth2/client/{client_key}/reset_secret Resets a client secret. For owner-only clients, this endpoint also resets the access token.
Response example
{
  "name": "Example",
  "client_key": "xxxxxxxxxx",
  "secret": "xxxxxxxxxx",
  "access_token": "xxxxxxxxxx"
}
Название Требуется? Описание По умолчанию
client_key Да client identifier
reason Нет string containing the reason for resetting the secret. ''
POST
/oauth2/client Creates an OAuth 2.0 client.
Response example
{
  "name": "Example",
  "client_key": "xxxxxxxxxx",
  "secret": "xxxxxxxxxx",
  "access_token": "xxxxxxxxxx"
}
Название Требуется? Описание По умолчанию
name Да client name
description Да client description
email Да contact email
is_confidential Да set to true if the client is confidential; set to false for public clients like mobile and desktop apps
grant_types Да OAuth 2.0 grant types used by the client, one or more of the following: authorization_code, refresh_token, client_credentials
scopes Да OAuth 2.0 scopes, either mwoauth-authonly, mwoauth-authonlyprivate or the set of applicable grants
version Нет client version. 1.0
wiki Нет applicable project. * for all wikis
owner_only ? set to true for a client used only by the creating user
callback_url Нет Return URL for authorizing users. ''
callback_is_prefix Нет set to true to allow the client to specify a callback in requests and use the callback URL as a required prefix. false
POST
If OAuth credentials are shared over a wiki farm, make sure that real names are used/hidden consistently across all wikis (using $wgHiddenPrefs ). On wikis where real names are hidden, the OAuth permission request message that tells the user which information is shared does not mention the real name, so in that case there should not be any other wiki where the OAuth consumer may still get that information from.

Experimental REST endpoints

To enable the experimental REST endpoints, add the $wgRestAPIAdditionalRouteFiles configuration variable to your LocalSettings.php:

$wgRestAPIAdditionalRouteFiles[] = "$wgExtensionDirectory/OAuth/experimentalRoutes.json";

См. также

  • Расширение:OATHAuth - A similarly named extension which implements a second authentication factor using OATH-based one-time passwords.
  • Extension:WSOAuth A MediaWiki extension that lets your wiki delegate authentication to any OAuth provider using PluggableAuth, including a wiki that is running Extension:OAuth.
  • oauthclient-php A client library for OAuth consumers.