Extension:CASAuthentication

From MediaWiki.org
Jump to: navigation, search

This version of the CAS Authentication plug-in is an attempt to implement CAS Authentication in MediaWiki 1.13+ without having to edit any of the core application files, but by using Hooks. It is based on a previous version by Christophe Naslain.

Feel free to suggest improvements.


MediaWiki extensions manual
Crystal Clear action run.png
CASAuthentication

Release status: beta

Implementation User activity
Description Overrides MediaWiki's Authentication and implements Central Authentication Service (CAS) Authentication
Author(s) Ioannis Yessios (yianniytalk)
Latest version 1.1e (November 8, 2011)
MediaWiki 1.13+
License GNU General Public License
Download No link
Hooks used
UserLoadFromSession

UserLogoutComplete
GetPreferences

Translate the CASAuthentication extension if it is available at translatewiki.net

Check usage and version matrix; code metrics

What can this extension do?[edit | edit source]

This extension implements Central Authentication Service (CAS) authentication in place of MediaWiki's standard authentication.

Requirements[edit | edit source]

You need the phpCAS php classes in order to use this extension (note: phpCAS need curl, openssl, zlib and dom php extensions compiled).

Installation[edit | edit source]

In your extensions directory, create a folder called CASAuth. In the new directory, create a file called CASAuth.php from the code included below.

You then need to extract phpCAS inside the new CASAuth directory. Rename the phpCAS directory to "CAS" (from something like "CAS-1.2.2"), or edit the configuration variable to point to the directory.

Then add the following to LocalSettings.php:

require_once("$IP/extensions/CASAuth/CASAuth.php");
 
//You can optionally use this if you want to keep your own configuration settings in LocalSettings.php instead of in CASAuth.php
//Parameters not specified here will use the default setting in CASAuth.php
$CASAuth = array_merge($CASAuth, array(
	"Server"         => "",
	"Port"           => 443,
	"Url"            => "/cas/",
	"Version"        => "1.0",
	"PwdSecret"      => "a random string of letters",
	"EmailDomain"    => "",
));

Configuration parameters[edit | edit source]

There is a single array with configuration variables:

  • phpCAS - Path to phpCAS directory.
  • Server - Address to CAS server.
  • Port - Port to CAS server. Default: 443.
  • Url - Subdir to CAS authentication.
  • Version - CAS version, should be either 1.0 or 2.0.
  • CreateAccounts - Should CASAuth create accounts on the wiki? Should be true unless all accounts already exists on the wiki!
  • PwdSecret - A random string that is used when generating the MediaWiki password for this user. YOU SHOULD EDIT THIS TO A VERY RANDOM STRING! YOU SHOULD ALSO KEEP THIS A SECRET!
  • EmailDomain - The default domain for new users email address (is appended to the username).
  • RememberMe - Log in users with the 'Remember me' option.

About CreateAccounts[edit | edit source]

If the user you are logging in as does not exist on the wiki, and this extension is not configured to automatically create accounts, then you will show up as an anonymous user. Just because you are logging in via a CAS server, that does not mean you do not need an account on the wiki. This extension only makes logging in a lot easier (and the user will be oblivious to the fact that an account has been created on the wiki).

Logging in without CAS[edit | edit source]

Even though you've installed this extension, you might have a need to log in to "non-CAS" users. They might be users you made before installing CAS. The easy way to do this is to first login with a CAS user, then go to Special:UserLogin and you will see the normal login box. You can now use it to login to your non-CAS user.

Code[edit | edit source]

<?php
/*
 * CASification script for MediaWiki 1.13 with phpCAS 0.6.0-RC5
 * 
 * Requires phpCAS: http://www.ja-sig.org/wiki/display/CASC/phpCAS
 * Install by adding this line to LocalSetting.php:
 *  require_once("$IP/extensions/CASAuth/CASAuth.php");
 * 
 * Remember to edit the configuration below!
 * Also consider restricting normal account creation:
 *  http://www.mediawiki.org/wiki/Manual:Preventing_access#Restrict_account_creation
 * You can disable the IP in the header which appears after logging out:
 *  http://www.mediawiki.org/wiki/Manual:$wgShowIPinHeader
 * 
 * 
 * Author: Ioannis Yessios (ioannis [dot] yessios [at] yale [dot] edu)
 * Worked with the code by Christophe Naslain ( chris [dot] n [at] free [dot] fr)
 * Which was based on the original script using CAS Utils by Victor Chen (Yvchen [at] sfu [dot] ca)
 * Cleaned up and bugfixed by Stefan Sundin (recover89@gmail.com)
 */
 
$wgExtensionCredits["other"][] = array(
	"name"        => "CASAuth",
	"version"     => "1.1e",
	"author"      => "Ioannis Yessios",
	"url"         => "http://www.mediawiki.org/wiki/Extension:CASAuthentication",
	"description" => "Overrides MediaWiki's Authentication and implements Central Authentication Service (CAS) Authentication"
);
 
//--------------------------------------------------------------------------
// Configuration Variables
//--------------------------------------------------------------------------
 
$CASAuth = array(
	"phpCAS"         => "$IP/extensions/CASAuth/CAS", // Path to phpCAS directory.
	"Server"         => "secure.its.yale.edu",        // Address to CAS server.
	"Port"           => 443,                          // Port to CAS server. Default: 443.
	"Url"            => "/cas/servlet/",              // Subdir to CAS authentication.
	"Version"        => "1.0",                        // CAS version, should be either 1.0 or 2.0.
	"CreateAccounts" => true,                         // Should CASAuth create accounts on the wiki? Should be true unless all accounts already exists on the wiki!
	"PwdSecret"      => "a random string of letters", // A random string that is used when generating the MediaWiki password for this user. YOU SHOULD EDIT THIS TO A VERY RANDOM STRING! YOU SHOULD ALSO KEEP THIS A SECRET!
	"EmailDomain"    => "yale.edu",                   // The default domain for new users email address (is appended to the username).
	"RememberMe"     => true,                         // Log in users with the 'Remember me' option.
);
 
//--------------------------------------------------------------------------
// CASAuth
//--------------------------------------------------------------------------
 
// Setup hooks
global $wgHooks;
$wgHooks["UserLoadFromSession"][] = "casLogin";
$wgHooks["UserLogoutComplete"][] = "casLogout";
$wgHooks["GetPreferences"][] = "casPrefs";
 
// Login
function casLogin($user, &$result) {
	global $CASAuth;
	global $IP, $wgLanguageCode, $wgRequest, $wgOut;
 
	if (isset($_REQUEST["title"])) {
 
		$lg = Language::factory($wgLanguageCode);
 
		if ($_REQUEST["title"] == $lg->specialPage("Userlogin")) {	
			// Initialize the session
			session_start();
 
			// Setup for a web request
			require_once("$IP/includes/WebStart.php");
 
			// Load phpCAS
			require_once($CASAuth["phpCAS"]."/CAS.php");
			phpCAS::client($CASAuth["Version"], $CASAuth["Server"], $CASAuth["Port"], $CASAuth["Url"], false);
			phpCAS::setNoCasServerValidation();
			phpCAS::forceAuthentication(); //Will redirect to CAS server if not logged in
 
			// Get username
			$username = phpCAS::getUser();
 
			// Get MediaWiki user
			$u = User::newFromName($username);
 
			// Create a new account if the user does not exists
			if ($u->getID() == 0 && $CASAuth["CreateAccounts"]) {
				// Create the user
				$u->addToDatabase();
				$u->setRealName($username);
				$u->setEmail($username."@".$CASAuth["EmailDomain"]);
				$u->setPassword( md5($username.$CASAuth["PwdSecret"]) ); //PwdSecret is used to salt the username, which is then used to create an md5 hash which becomes the password
				$u->setToken();
				$u->saveSettings();
 
				// Update user count
				$ssUpdate = new SiteStatsUpdate(0,0,0,0,1);
				$ssUpdate->doUpdate();
			}
 
			// Login successful
			if ($CASAuth["RememberMe"]) {
				$u->setOption("rememberpassword", 1);
			}
			$u->setCookies();
			$user = $u;
 
			// Redirect if a returnto parameter exists
			$returnto = $wgRequest->getVal("returnto");
			if ($returnto) {
				$target = Title::newFromText($returnto);
				if ($target) {
					$wgOut->redirect($target->getFullUrl()."&action=purge"); //action=purge is used to purge the cache.
				}
			}
		}
		else if ($_REQUEST["title"] == $lg->specialPage("Userlogout")) {
			// Logout
			$user->logout();
		}
	}
 
	// Back to MediaWiki home after login
	return true;
}
 
// Logout
function casLogout() {
	global $CASAuth;
	global $wgUser, $wgRequest;
 
	// Logout from MediaWiki
	$wgUser->doLogout();
 
	// Get returnto value
	$returnto = $wgRequest->getVal("returnto");
	if ($returnto) {
		$target = Title::newFromText($returnto);
		if ($target) {
			$redirecturl = $target->getFullUrl();
		}
	}
 
	// Logout from CAS (will redirect user to CAS server)
	require_once($CASAuth["phpCAS"]."/CAS.php");
	phpCAS::client($CASAuth["Version"], $CASAuth["Server"], $CASAuth["Port"], $CASAuth["Url"], false);
	if (isset($redirecturl)) {
		phpCAS::logoutWithRedirectService($redirecturl);
	}
	else {
		phpCAS::logout();
	}
 
	return true; // We won't get here
}
 
// Remove reset password link and remember password checkbox from preferences page
function casPrefs($user, &$preferences) {
	unset($preferences["password"]);
	unset($preferences["rememberpassword"]);
	return true;
}

LDAP connection[edit | edit source]

This improvement works only in combination with Extension:External_Data. It sets the RealName and Email to more useful data from LDAP.

#       $u->setRealName($username);
#       $u->setEmail($username."@".$CASAuth["EmailDomain"]);
        //get data from LDAP
        $results = EDUtils::getLDAPData( "(uid=$username)", "domain", array("sn","givenname","mail") );
        if ( $results[count] == 1 ) {
          $myGivenname = $results[0]["givenname"][0];
          $mySn       = $results[0]["sn"][0];
          $myMail     = $results[0]["mail"][0];
          $u->setRealName($myGivenname." ".$mySn);
          $u->setEmail($myMail);
          $u->confirmEmail();
        }
 
        //add after: $u->saveSettings();
        wfRunHooks( 'AddNewAccount', array( $u ) );

Improve[edit | edit source]

Example is for openLDAP, maybe it should be improved with settings from LocalSettings.php with Hook for realname and emailaddress

  • uid
  • "domain" to fetch settings for EDUtils::getLDAPData from LocalSettings.php see LDAP config
  • array("sn","givenname","mail")) array to search in LDAP
  • extend: disableChangeRealname, disableChangeEmail
  • update data on login