Расширение:CentralAuth
CentralAuth allows merging several existing separate account systems into one global account system.
Установка
Смотрите ниже раздел Настройка, чтобы увидеть список настроек, требуемых для использования CentralAuth. Затем, когда вы будете готовы начать использовать CentralAuth, следуйте инструкциям ниже:
- Установите Расширение:AntiSpoof , так как это обязательная зависимость.
- Скачайте последнюю версию расширения и распакуйте её в директорию
extensions
. - Выберите базу данных и создайте в ней таблицы CentralAuth. Вы можете использовать существующую или создать новую БД; расширение по умолчанию использует БД с именем $1 (см. $2 ниже). (The extension by default uses the wiki's local database, which is convenient for automated testing but doesn't really make sense on a real wiki farm (as it will be different for every wiki, but the point of CentralAuth is sharing data between wikis) so you'll need to reconfigure that; see
$wgVirtualDomainsMapping['virtual-centralauth']
below.) После того, как вы выберете БД, запуститеtables-generated.sql
.- Если вы используете Расширение:AntiSpoof , вам также потребуется создать глобальную таблицу
spoofuser
(это нужно для того, чтобы блокировать возможность создания новых аккаунтов, чьи имена похожи на имена уже зарегистрированных в любой из ваших вики). Это можно сделать, например, выгрузив таблицуspoofuser
из БД локальной вики и импортировав её в$wgVirtualDomainsMapping['virtual-centralauth']
.
- Если вы используете Расширение:AntiSpoof , вам также потребуется создать глобальную таблицу
- Добавьте
wfLoadExtension( 'CentralAuth' );
в LocalSettings.php каждой ваших вики, или в другой PHP-файл, включённый вLocalSettings.php
на каждой из ваших вики. - Теперь расширение должно стать активным.
Создание новой базы данных
Here are sample shell and SQL commands to create the centralauth
database, copy the spoofuser
table to it, and migrate existing user data to it.
Replace $wgDBname and $wgDBuser with the values for your own wiki installation credentials.
Create the new database (Remember this step is optional, you can instead use one of your existing databases, in which case skip to the create tables step):
$ cd extensions/CentralAuth
$ mysql -u root -p
(введите пароль для пользователя root SQL)
CREATE DATABASE centralauth;
USE centralauth;
GRANT all on centralauth.* to '$wgDBuser'@'localhost';
quit
Запуск скриптов обслуживания
The following assumes your present working directory is your MediaWiki installation (not your CentralAuth directory).
Create the central auth tables (using sql.php
is preferred).
php maintenance/run.php sql --wikidb centralauth extensions/CentralAuth/schema/<db_type>/tables-generated.sql
If AntiSpoof is installed, create the table via (Alternatively, you can copy an existing AntiSpoof table if you want to keep previous entries):
php maintenance/run.php sql --wikidb centralauth extensions/AntiSpoof/sql/<db_type>/tables-generated.sql
Run the user migration scripts
$ php maintenance/run.php CentralAuth:migratePass0.php
$ php maintenance/run.php CentralAuth:migratePass1.php
Обновление
CentralAuth is designed for large wiki farms who run database updates manually in order to enable zero-downtime upgrades. For that reason, the CentralAuth database will not be updated with the usual upgrade process. Third-party users are expected to follow CentralAuth development and apply database migrations manually instead.
Настройка
First, you'll need to configure your wiki family using $wgConf
, or CentralAuth can't be used for your wiki family.
This includes setting $wgLocalDatabases
and assigning it to $wgConf->wikis
, and $wgConf->settings
(minimum is $wgCanonicalServer
, $wgServer
and $wgArticlePath
).
Внимательно следуйте примерам.
If you are creating a new wiki family, bear in mind that it may be easier if the databases for the wikis in each group have the same suffix (e.g. hypothetical databases enwiki
, dewiki
, frwiki
, etc., pertaining to wikis belonging to the same group, all have the suffix "wiki
").
After installing the extension, you have to gather some data in the CentralAuth database. In order to retroactively set up global accounts, you will have to run the migratePass0.php and migratePass1.php scripts. The first one stores information about your wikis in the CentralAuth database, while the second one uses automatic migration heuristics to generate global accounts. Пользователь может объединить свои аккаунты вручную с помощью Special:MergeAccount. Dry runs can be used for testing purposes.
To enable global groups, you will have to make an entry into the global_group_permissions
table in your CentralAuth database, with ggp_group='steward'
and (for access to the group management interface) ggp_permission=globalgrouppermissions
.
A sample query that is recommended to use is:
INSERT INTO global_group_permissions (ggp_group,ggp_permission) VALUES ('steward','globalgrouppermissions'), ('steward','globalgroupmembership');
Then, promote some users into stewards:
INSERT IGNORE INTO global_user_groups (gug_user, gug_group) VALUES ((SELECT gu_id FROM globaluser WHERE gu_name='Admin'), 'steward');
There are various settings you may wish to modify (e.g. whether to provide single sign-on across a whole domain) listed in CentralAuth.php.
In particular, you will want to set a value for $wgVirtualDomainsMapping['virtual-centralauth']
.
Make sure you put such settings after the wfLoadExtension
line in LocalSettings.php
, e.g.:
wfLoadExtension( 'CentralAuth' );
$wgVirtualDomainsMapping['virtual-centralauth'] = [ 'db' => 'centralauth' ];
"SUL2" behavior
In July 2013 WMF changed its approach to logging users into multiple wikis.
When configured for this new approach, after successful login and account creation CentralAuth redirects to Special:CentralLogin/start?token=somevalue
on a "central login wiki", which sets cookies on that wiki and then redirects back to the logged-into wiki.
It omits the "login/account creation success" page, instead redirecting back to the "returnto" page that the user was originally on.
It places 1x1 pixel images in the footer of that page, in place of the icons formerly used on the "login/account creation success" page.
The settings for this are, roughly,
# General CentralAuth configuration
$wgCentralAuthCookies = true;
// по умолчанию $1
$wgVirtualDomainsMapping['virtual-centralauth'] = [ 'db' => 'centralauthDatabaseName' ];
$wgCentralAuthAutoMigrate = true;
$wgCentralAuthAutoLoginWikis = [
# Mapping from domain name to wiki id for other wikis to automatically login into
'enwiki.mediawiki.mwdd.localhost' => 'enwiki',
];
# Activates the redirect to the "central login wiki"
$wgCentralAuthLoginWiki = 'WikiIdOfLoginWiki';
$wgCentralAuthLoginWiki
is the ID (usually the database-name) of the wiki to which CentralAuth will redirect on login and create account actions.
Проблемы с кешем
For best results, it is recommended to use memcached or a more persistent cache.
If you have only a single server, accelerator caches (CACHE_ACCEL
) like APCu can also work, but do not use them if you have multiple servers.
If you have no cache set up (i.e. CACHE_NONE
) for $wgMainCacheType
, or are using CACHE_DB
, then you need to make sure all your wikis use the same caching table.
By default, each wiki in your wiki farm will use the objectcache
table in its own database (with its own db prefix) when $wgMainCacheType
is set to CACHE_NONE
or CACHE_DB
.
To make this work with CentralAuth, we need to tell the wikis to use a central cache table.
If you want to make a central caching table in the centralauth
database (and assuming one of your existing wikis has a database name of enwiki
), run code like the following to copy the table to your other database (assuming you have an installed wiki with database called "enwiki" and another database called "centralauth"):
CREATE TABLE centralauth.objectcache LIKE enwiki.objectcache
Then add the following config to all wikis to tell them to use the central table instead of their own table:
$wgSharedDB = 'centralauth'; // or whatever database you use for central data
$wgSharedTables = [ 'objectcache' ]; // remember to copy the table structure's to the central database first
$wgCentralAuthSessionCacheType = CACHE_DB; // Tell mediawiki to use objectcache database for central auth.
When running PHPUnit tests locally with your wiki farm and do not want them to fail due to an attempt to clone database tables with the shared tables config above, use:
if ( defined( 'MW_PHPUNIT_TEST' ) ) {
$wgSharedTables = [];
} else {
$wgSharedTables = [ 'objectcache' ];
}
HTTP и HTTPS
Since 2023, CentralAuth does not support mixed-protocol HTTP/HTTPS wikis, only pure-HTTPS wikis (with $wgForceHTTPS set to true
) and pure-HTTP wikis (primarily for local testing).
See issue T348852.
Конфигурация
Database Virtual Domains Mapping
Since MediaWiki 1.41, you can configure database virtual domains mapping for CentralAuth, and this replaced $wgCentralAuthDatabase
.
To setup virtual domains mapping with CentralAuth, use:
// 'centralauth' is the name of the your CentralAuth database.
$wgVirtualDomainsMapping['virtual-centralauth'] = [ 'db' => 'centralauth' ];
параметр | по умолчанию | комментарий |
---|---|---|
(deprecated ) $wgCentralAuthDatabase
|
null
|
Database name you keep central auth data in.
If this is not on the primary database connection, don't forget to also set up To use a database with a table prefix, set this variable to " NOTE: This setting has been deprecated, use virtual domains mapping as described above. |
$wgCentralAuthAutoMigrate
|
false
|
If true , existing unattached accounts will be automatically migrated if possible at first login.
Any new account creations will be required to attach. If |
$wgCentralAuthAutoMigrateNonGlobalAccounts
|
false
|
If true , existing unattached accounts where no global account exists will be compared to see if a merge can be made based on passwords and emails with no clashes (all accounts merge).
This was formerly controlled by |
$wgCentralAuthStrict
|
false
|
If true , remaining accounts which have not been attached will be forbidden from logging in until they are resolved.
|
$wgCentralAuthDryRun
|
false
|
If true , merging won't actually be possible through the Special:MergeAccount interface.
|
$wgCentralAuthCookies
|
false
|
If true , global session and token cookies will be set alongside the per-wiki session and login tokens when users log in with a global account.
This allows other wikis on the same domain to transparently log them in. |
$wgCentralAuthLoginWiki
|
false
|
Database name of a central login wiki. This is an alternative to directly setting cross-domain cookies for each wiki in $wgCentralAuthAutoLoginWikis . If set, a single login wiki will use a session/cookie to handle unified login sessions across wikis.
On login, users will be redirected to the login wiki's Special:CentralLogin/login page and then redirected to Special:CentralLogin back on the originating wiki. In the process, the central login wiki cookie and session will be set. As the user accesses other wikis, the login wiki will be checked via JavaScript to check login status and set the local session and cookies. Это требует |
$wgCentralAuthCookieDomain
|
''
|
Domain to set global cookies for.
For instance, |
$wgCentralAuthCookiePrefix
|
'centralauth_'
|
Prefix for CentralAuth global authentication cookies. |
$wgCentralAuthCookiePath
|
'/'
|
Path for CentralAuth global authentication cookies. Set this variable if you want to restrict cookies to a certain path within the domain specified by $wgCentralAuthCookieDomain .
|
$wgCentralAuthAutoLoginWikis
|
[]
|
List of wiki IDs which should be called on login to try to set third-party cookies for the global session state.
The wiki ID is typically the database name, except when table prefixes are used, in which case it is the database name, a hyphen separator, and then the table prefix. This allows a farm with multiple second-level domains to set up a global session on all of them by hitting one wiki from each domain (en.wikipedia.org, en.wikinews.org, etc.). Done by accessing Если пусто, другие вики не будут затронуты. The key should be set to the cookie domain name. |
$wgCentralAuthAutoCreateWikis
|
[]
|
List of wiki IDs on which an attached local account should be created automatically when the global account is created.
The wiki ID is typically the database name, except when table prefixes are used, in which case it is the database name, a hyphen separator, and then the table prefix. |
$wgCentralAuthLoginIcon
|
false
|
Local filesystem path to the icon returned by Special:CentralAutoLogin should be a 20x20px PNG.
|
$wgCentralAuthPrefsForUIReload
|
[ 'skin', 'language', 'thumbsize', 'underline', 'stubthreshold', 'showhiddencats', 'justify', 'numberheadings', 'editondblclick', 'editsection', 'editsectiononrightclick', 'usenewrc', 'extendwatchlist' ]
|
User preferences for which we should recommend reloading the page after a successful central login query.
If you need to do something more complicated than just |
$wgCentralAuthRC
|
[]
|
Array of settings for sending the CentralAuth events to the RC Feeds.
|
$wgCentralAuthWikisPerSuppressJob
|
10
|
Size of wikis handled in one suppress user job. Keep in mind that one wiki requires ~10 queries.
|
$wgCentralAuthReadOnly
|
false
|
Like $wgReadOnly , used to set extension to database read only mode.
|
$wgCentralAuthEnableGlobalRenameRequest
|
false
|
Feature flag for Special:GlobalRenameRequest .
|
$wgCentralAuthGlobalPasswordPolicies
|
[]
|
Глобальные правила паролей. These are applied like local password policies, the strongest policy applicable to a user is used. Policies can apply to either a local group (if the user is a member of that group on any wiki, the policy will apply to that user) or global group.
|
$wgGlobalRenameDenylist
|
null
|
A list of users who won't be allowed to create new global rename requests through Special:GlobalRenameRequest.
Есть два способа установить его:
You can use the exact names or regular expressions.
|
$wgCentralAuthGlobalBlockInterwikiPrefix
|
"global"
|
When globally suppressing a user, a block against this user is inserted in all wikis. CentralAuth will set the author of theses blocks as $wgCentralAuthGlobalBlockInterwikiPrefix>(user-who-made-the-suppression's nickname) . Например, если $wgCentralAuthGlobalBlockInterwikiPrefix = "Admins"; , and Joe suppresses John, all wikis will show in BlockList a block against John made by Admins>Joe .
|
Использование
Allows for a single-user login (SUL) system using MediaWiki's AuthPlugin system. User creation and login is done globally using one central user table across all wikis. Note that local user accounts are automatically created on account creation/login however.
This extension also implements global user groups, to which global accounts can belong to.
Права пользователей
CentralAuth defines several new user rights:
Право пользователя | Способности | Группа по умолчанию | Статус |
---|---|---|---|
centralauth-createlocal
|
Forcibly create a local account for a global account | Stewards and sysops | Active in MW 1.36+ |
centralauth-lock
|
Prevent users from logging in on any wiki | Стюарды | Активно |
centralauth-suppress
|
Suppress or unhide global accounts | Стюарды | Active |
centralauth-rename
|
Rename global accounts | Стюарды | Active |
centralauth-unmerge
|
Unmerge global accounts from a local account | Стюарды | Active |
centralauth-merge
|
Merge all CentralAuth accounts globally | All users | Active; usually automatic |
globalgrouppermissions
|
Manage permissions of global groups | Глобальные стюарды | Active; not assigned to local stewards by default |
globalgroupmembership
|
Edit membership to global groups | Глобальные стюарды | Active; not assigned to local stewards by default |
Функции
Single-user login (SUL)
A user with an account on more than one wiki may use Special:MergeAccount to create their global user account, which can then be used on any wiki. Users with the centralauth-unmerge
permission (given to stewards by default) can undo a merging of a global account, where the passwords are all reset back to the pre-merge setting.
User accounts can now also be renamed globally.
Locking and hiding global users
A global account can be locked or hidden by a user with the centralauth-lock
and centralauth-suppress
permissions, respectively, given to the local group 'stewards' by default.
A locked global account will be immediately logged out of any session on any wiki it is currently logged in to.
A hidden global account's username is not visible in any logs except the global account log.
Wiki sets
A wiki set is a group of wikis specified by a user with the globalgrouppermissions
right.
Sets can be opt-in (wikis are not in it by default) or opt-out (wikis are in it unless opted out).
Глобальные права пользователей
Once you have enabled global user groups as described in the installation section, a migrated steward can use the Special:GlobalGroupPermissions interface to configure global user groups, and their rights.
A global user group is active on all wikis (the users in it have its rights on all the wikis) by default, unless the group has been specified to only be active on a specific wiki set (the users in the group only have the rights if they are on a wiki in the set).
Global group permissions are not listed at Special:ListUsers, but instead Special:GlobalUsers.
They are assigned by a user with the globalgroupmembership
permission (by default the global group stewards
), and give the specified rights to the user even if the local rights defined by $wgGroupPermissions
do not do so.
Лицензирование и загрузки
The extension is available under the GNU General Public License 2.0 or later, and can be downloaded from Git, or accessed via the web-based viewer.
Программное обеспечение предоставляется как есть. Updates will be made according to the needs of Wikimedia wikis; or where critical vulnerabilities are discovered.
API
Смотрите Extension:CentralAuth/API .
Примечания
Смотрите также
- Help:Unified login on Meta-Wiki
- Extension:CentralAuth/authentication - CentralAuth authentication features
$wgSharedDB
- User:Legoktm/evil-plans2.txt - 2015 plan to phase out CentralAuth at WMF
- Global session threat assessment
- w:Wikipedia:Integrated watchlists
- Поток управления CentralAuth
- Stuck global renames
Это расширение используется в одном или нескольких проектах Викимедиа. Вероятно, это означает, что расширение стабильно и работает достаточно хорошо, чтобы использоваться такими сайтами с высоким трафиком. Найдите название этого расширения в файлах конфигурации Викимедиа CommonSettings.php и InitialiseSettings.php, чтобы узнать, где оно установлено. Полный список расширений, установленных на конкретной вики, можно увидеть на странице Special:Version wiki. |
Это расширение включено в следующие вики-фермы/хостинги и/или пакеты: Это не исчерпывающий список. Некоторые вики-фермы/хостинги и/или пакеты могут содержать это расширение, даже если они не перечислены здесь. Всегда сверяйтесь со своими вики-фермами/хостингами или комплектами/бандлами для подтверждения. |
- Stable extensions/ru
- User identity extensions/ru
- Database extensions/ru
- Special page extensions/ru
- API extensions/ru
- GPL licensed extensions/ru
- Extensions in Wikimedia version control/ru
- APIGetAllowedParams extensions/ru
- AbuseFilter-builder extensions/ru
- AbuseFilter-computeVariable extensions/ru
- AbuseFilter-generateUserVars extensions/ru
- AbuseFilterAlterVariables extensions/ru
- AbuseFilterShouldFilterAction extensions/ru
- ApiCheckCanExecute extensions/ru
- ApiQueryCheckCanExecute extensions/ru
- ApiQueryTokensRegisterTypes extensions/ru
- AuthChangeFormFields extensions/ru
- AuthManagerFilterProviders extensions/ru
- AuthManagerVerifyAuthentication extensions/ru
- AuthPreserveQueryParams extensions/ru
- AutopromoteCondition extensions/ru
- BeforePageDisplay extensions/ru
- ContentSecurityPolicyDefaultSource extensions/ru
- ContentSecurityPolicyScriptSource extensions/ru
- ContributionsToolLinks extensions/ru
- GetLocalURL extensions/ru
- GetLogTypesOnUser extensions/ru
- GetPreferences extensions/ru
- GetUserBlock extensions/ru
- ImportHandleUnknownUser extensions/ru
- InvalidateEmailComplete extensions/ru
- LoadExtensionSchemaUpdates extensions/ru
- LocalUserCreated extensions/ru
- LogEventsListGetExtraInputs extensions/ru
- MakeGlobalVariablesScript extensions/ru
- OtherBlockLogLink extensions/ru
- PasswordPoliciesForUser extensions/ru
- PostLoginRedirect extensions/ru
- RenameUserComplete extensions/ru
- RenameUserPreRename extensions/ru
- RenameUserWarning extensions/ru
- ResourceLoaderForeignApiModules extensions/ru
- ResourceLoaderModifyEmbeddedSourceUrls extensions/ru
- SecurePoll GetUserParams extensions/ru
- SessionCheckInfo extensions/ru
- SetupAfterCache extensions/ru
- SpecialContributionsBeforeMainOutput extensions/ru
- SpecialLogAddLogSearchRelations extensions/ru
- SpecialPageBeforeExecute extensions/ru
- SpecialPage initList extensions/ru
- SpecialPasswordResetOnSubmit extensions/ru
- TempUserCreatedRedirect extensions/ru
- TestCanonicalRedirect extensions/ru
- UnitTestsAfterDatabaseSetup extensions/ru
- UnitTestsBeforeDatabaseTeardown extensions/ru
- UserArrayFromResult extensions/ru
- UserEditCountUpdate extensions/ru
- UserGetEmail extensions/ru
- UserGetEmailAuthenticationTimestamp extensions/ru
- UserGetReservedNames extensions/ru
- UserGetRights extensions/ru
- UserIsBot extensions/ru
- UserIsLocked extensions/ru
- UserLoginComplete extensions/ru
- UserLogout extensions/ru
- UserLogoutComplete extensions/ru
- UserSaveSettings extensions/ru
- UserSetEmail extensions/ru
- UserSetEmailAuthenticationTimestamp extensions/ru
- GetUserPermissionsErrors extensions/ru
- GetUserPermissionsErrorsExpensive extensions/ru
- All extensions/ru
- Extensions used on Wikimedia/ru
- Extensions included in Miraheze/ru
- Extensions included in Telepedia/ru
- Extensions included in WikiForge/ru
- CentralIdLookup providers/ru
- Login extensions/ru