Hacking Auth on MediaWiki

2007-01-08 2-minute read

For some explanation of how to hack your own auth system into MediaWiki, a couple good resources are:

http://meta.wikimedia.org/wiki/User:Otheus/Auto_Login_via_REMOTE_USER http://www.x-tend.be/~raskas/blog/2006/11/17/mediawiki-remote-user-authentication

I wanted to do someting a little different:

  • Rather than use HTTP Auth, I wanted to use MediaWiki’s login form and authenticate against a different database.
  • I also did not want any user who is not authenticated to be able to view the wiki at all.
  • And, I wanted users that I choose to be able to register and login properly.

Here are the steps I took - many thanks to Raska!

  • Copy includes/AuthPlugin.php to a different file with a new name (such as mfpl_auth_plugin.inc.php)

  • Edit the file

    // Include the original file (change path as needed) include (’/usr/share/mediawiki/includes/AuthPlugin.php’); // Optionally include any libraries you might personally // use for authentication here

    // Give the class a new name and extend the original class class mfpl_auth_plugin extends AuthPlugin {

    // define a new constructor function // this function adds a new function that is always called on // page loads (it will be described below) function mfpl_auth_plugin() { global $wgExtensionFunctions; if (!isset($wgExtensionFunctions)) { $wgExtensionFunctions = array(); } else if (!is_array($wgExtensionFunctions)) { $wgExtensionFunctions = array( $wgExtensionFunctions ); } array_push($wgExtensionFunctions, ‘Auth_remote_user_hook’); }

    // Review the remaining functions - I only modified the authentice // function

  • Add a new function to the bottom of the file
    function Auth_remote_user_hook()
    {
    global $wgUser;
    global $wgRequest;
    
    // For a few special pages, don't do anything.
    $title = $wgRequest->getVal('title') ;
    if ($title == 'Special:Userlogout' ||
    $title == 'Special:Userlogin') {
    return;
    }
    
    $wgUser = User::loadFromSession();
    $username = strtolower($wgUser->getName());
    global $wgAllowedUsers,$IP;
    if(in_array($username,$wgAllowedUsers))
    {
    // Do nothing if session is valid
    if ($wgUser->isLoggedIn()) {
    return;
    }
    }
    
    // If it is not valid log them out
    include("$IP/includes/SpecialUserlogout.php");
    wfSpecialUserLogout();
    }
    
  • Edit your LocalSettings.php file
    // Add to the bottom of the file (change path as appropriate):
    require_once('/path/to/mfpl_auth_plugin.inc.php');
    $wgAuth = new mfpl_auth_plugin();
    $wgAllowedUsers = array(
    'joe','susie','jane'
    );