MediaWiki 1.31升级:AuthManager与SessionManager外部用户认证求助
Hey there! I’ve been through the exact same upgrade pain when moving from 1.24 to the newer LTS versions, so I know how confusing the AuthManager/SessionManager switch can be. Let’s walk through practical, working examples for both scenarios you need: authenticating an existing user, and creating + authenticating a new user when they don’t exist locally.
Core Concepts to Keep in Mind
Before diving into code, let’s clarify the new system to avoid confusion:
- AuthManager: The central class handling all authentication logic (replacing the old
LoginFormhacks). We’ll use it to validate our external user’s identity. - SessionManager: Manages user sessions post-authentication—this is what keeps the user logged in across requests.
- AuthenticationRequest: A helper class that carries user identity data to AuthManager (think of it as the "proof" the user is who they claim to be).
Example 1: Authenticate an Existing User (Known Username/User ID)
If you already know the user exists in your MediaWiki database, here’s how to log them in programmatically:
use MediaWiki\Auth\AuthManager; use MediaWiki\Session\SessionManager; use MediaWiki\User\User; // 1. Fetch the existing user object (use either username or user ID) $username = 'ExternalUser123'; $user = User::newFromName( $username ); if ( !$user || $user->isAnon() ) { // Handle case where user doesn't exist (we'll cover this next) return; } // 2. Create a custom AuthenticationRequest to carry the user's identity // We're skipping user input here because we trust the external system's data $authRequest = new class extends MediaWiki\Auth\AuthenticationRequest { public $username; public function getFieldInfo() { return []; // No input fields needed for this flow } public function getUniqueId() { return 'CustomExternalAuth'; // Unique ID for our auth flow } }; $authRequest->username = $username; // 3. Use AuthManager to authenticate the user $authManager = AuthManager::singleton(); $status = $authManager->authenticate( [ $authRequest ] ); if ( $status->isOK() ) { // 4. Set up the user session to keep them logged in $session = SessionManager::getGlobalSession(); $session->setUser( $user ); $session->persist(); // Optional: Update the user's last login timestamp $user->setLastLogin( wfTimestampNow() ); $user->saveSettings(); echo "User $username logged in successfully!"; } else { // Handle authentication failure (e.g., invalid user, permissions issue) echo "Authentication failed: " . $status->getMessage()->text(); }
Example 2: Create a New User & Authenticate Them
If the external user doesn’t exist in your MediaWiki instance, we’ll first create the user, then proceed with authentication:
use MediaWiki\Auth\AuthManager; use MediaWiki\Session\SessionManager; use MediaWiki\User\User; use MediaWiki\MediaWikiServices; // 1. Check if the user already exists $username = 'NewExternalUser456'; $userFactory = MediaWikiServices::getInstance()->getUserFactory(); $user = $userFactory->newFromName( $username ); if ( !$user || $user->isAnon() ) { // 2. Create the new user (ensure $wgAutoCreateTempUser is enabled or you have create permissions) $user = User::createNew( $username, [ 'email' => 'user@externalsystem.com', // Optional: Add email if available 'real_name' => 'John Doe' // Optional: Add real name ] ); if ( $user->isError() ) { // Handle user creation failure (e.g., invalid username, duplicate) echo "Failed to create user: " . $user->getError(); return; } echo "New user $username created successfully!"; } // 3. Authenticate the user (same flow as Example 1) $authRequest = new class extends MediaWiki\Auth\AuthenticationRequest { public $username; public function getFieldInfo() { return []; } public function getUniqueId() { return 'CustomExternalAuth'; } }; $authRequest->username = $username; $authManager = AuthManager::singleton(); $status = $authManager->authenticate( [ $authRequest ] ); if ( $status->isOK() ) { $session = SessionManager::getGlobalSession(); $session->setUser( $user ); $session->persist(); $user->setLastLogin( wfTimestampNow() ); $user->saveSettings(); echo "User $username logged in successfully!"; } else { echo "Authentication failed: " . $status->getMessage()->text(); }
A Quick Note on PluggableAuth/PluggableSSO
If you want to avoid writing custom code, PluggableAuth is a great option—it abstracts most of the AuthManager boilerplate. Here’s a simplified setup for your use case:
- Install PluggableAuth and PluggableSSO extensions.
- Add this to your
LocalSettings.php:$wgPluggableAuth_EnableAutoCreate = true; // Auto-create users if they don't exist $wgPluggableAuth_Config = [ 'MyExternalSSO' => [ 'plugin' => 'PluggableSSO', 'data' => [] // We'll inject user data via a hook ] ]; - Use the
PluggableAuthAuthenticationProviderhook in a custom extension to pass external user data:$wgHooks['PluggableAuthAuthenticationProvider'][] = function( &$provider, &$data ) { // Pull username/email/realname from your external system $data['username'] = 'ExternalUser789'; $data['email'] = 'user@externalsystem.com'; $data['realname'] = 'Jane Smith'; return true; };
PluggableAuth will handle creating the user if missing and authenticating them automatically—no need to mess with AuthManager directly.
Important Notes
- Permissions: Make sure your code has the necessary permissions to create users (check
$wgGroupPermissions['*']['createaccount']if allowing auto-creation). - Security: Always validate the external user’s identity before authenticating them—never trust arbitrary input!
- Session Persistence: Calling
$session->persist()is crucial to keep the user logged in across page reloads.
内容的提问来源于stack exchange,提问作者Andy Johnson

