Extension:Shibboleth Authentication

Overview
Shibboleth is a Single Signon identity managment solution that's a project of Internet2. It's in use not only in many universities through the US and elsewhere but also on sites such as openidp to provide authentication to a range of applications. This extension allows mediawiki to use Shibboleth as an external authentication source.

Current Version: 1.1.4

Compatibility
This extension is designed for MediaWiki 1.7 and up. If you want to use this extension with the 1.6 branch or earlier look at bugs 5819 and 6006 and apply the SVN changes that took place.

Shibboleth Configuration
The extension requires that shibboleth be configured and set up on the web server the wiki is hosted on. Once Shibboleth is running on the web server make sure your configuration file is correctly set-up. Your IdP should be able to help you with this. The extension uses lazy sessions and a WAYF url so you'll want to verify these are setup as well. (You can actually use full sessions if you want, but the extension is designed to use lazy sessions to allow for the standard wiki auth to co-exist alongside.) You'll need to tell the extension which WAYF url to use.

The part of the configuration file (shibboleth.xml) where a WAYF url will be present is here: ...   

For lazy sessions in Apache, the following lines in your apache configuration files will do: ...  AuthType shibboleth Require shibboleth 

If you don't want lazy sessions but instead would rather require shibboleth authentication, then use: ...  AuthType shibboleth ShibRequireSession On       Require valid-user 

Download the Extension
The code for the extension is at the bottom of this page. Go ahead and place that in a file in the extensions folder called ShibAuthPlugin.php.

Extension Configuration
Now it's time to configure and load the extension. To do that, just add the following lines to LocalSettings.php in the root of the mediawiki directory.

Most of the configuration directives are of the form: $shib_SOMELETTERS = data_manipulation_functions($_SERVER['HEADER_FOR_SHIB_DATA']); This allows you to map whatever shibboleth identifers you chose to a variety of fields for each user as well as use the standard PHP functions to massage the data as it enters. All the Shibboleth data has been placed in the $_SERVER superglobal by the Shibboleth module and should be available. You may need to run a script like the following to determine exactly what data is available: <? //Drop this into a directory where sessions are required //or where you are already authenticated and then simply //access it to see the mapping. while(list($index, $data) = each($_SERVER)) {	echo "$index -> $data "; } ?>

At the very minimum you'll need to make the following changes:
 * 1) Place the following code into the LocalSettings.php file.
 * 2) Set the WAYF url.
 * 3) Map a valid piece of Shib data for the username.
 * 4) Look over the rest of the variables and ensure that you don't want to make any more changes.

require_once('extensions/ShibAuthPlugin.php');
 * 1) Shibboleth Authentication Stuff
 * 2) Load ShibAuthPlugin

$shib_WAYF = "idp.example.org";
 * 1) Last portion of the shibboleth WAYF url for lazy sessions.
 * 2) This value is found in your shibboleth.xml file on the setup for your SP
 * 3) WAYF url will look something like: /Shibboleth.sso/WAYF/$shib_WAYF

$shib_Https = true;
 * 1) Is the assertion consumer service located at an https address (highly recommended)
 * 2) Default for compatibility with previous version: false

$shib_LoginHint = "Login via Single Sign-on";
 * 1) Prompt for user to login

$shib_AssertionConsumerServiceURL = "/Shibboleth.sso";
 * 1) Where is the assertion consumer service located on the website?
 * 2) Default: "/Shibboleth.sso"

$shib_map_info = "true";
 * 1) Do you want to map in names from Shibboleth data?
 * 2) Feel free to use extra PHP code to munge the variables if you'd like
 * 3) Additionally if you wish to only map some of the name data, set this to true
 * 4) and either blank shib_RN and shib_email or comment them out entirely.

$olderror = error_reporting(E_ALL ^ E_NOTICE);
 * 1) Ssssh.... quiet down errors

$shib_RN = ucfirst(strtolower($_SERVER['HTTP_FIRST_NAME'])). ' '	 . ucfirst(strtolower($_SERVER['HTTP_LAST_NAME']));
 * 1) Map Real Name to what Shibboleth variable(s)?

$shib_email = $_SERVER['HTTP_EMAIL'];
 * 1) Map e-mail to what Shibboleth variable?

$shib_UN = strtolower($_SERVER['HTTP_EMAIL']);
 * 1) This is required to map to something
 * 2) You should beware of possible namespace collisions, it is best to chose
 * 3) something that will not violate MW's usual restrictions on characters
 * 4) Map Username to what Shibboleth variable?


 * 1) Shibboleth doesn't really support logging out very well. To take care of
 * 2) this we simply get rid of the logout link when a user is logged in through
 * 3) Shib. Alternatively, you can uncomment and set the variable below to a link
 * 4) that will either clear the user's cookies or log the user out of the Idp and
 * 5) instead of deleting the logout link, the extension will change it instead.
 * 6) $shib_logout = "http://example.org";

error_reporting($olderror);
 * 1) Turn error reporting back on

SetupShibAuth;
 * 1) Activate Shibboleth Plugin

Using the Extension
The extension is designed to be fairly simple to use. Once everything is configured and Shibboleth is running a link will appear at the top right hand corner of the screen next to the normal mediawiki login link that says "login via single sign-on." Clicking this link will bounce the user to the WAYF url which will pass them to the IdP for authentication. When they come back they'll be logged in.

Adding more Metadata
If you wish to add more mappings from Mediawiki data to Shibboleth data than is available, you can simply add them in the configuration file. The only code changes you will have to do are in the updateUser function of the ShibAuthPlugin.php file.

Logout Functionality
Shibboleth currently has no good way to log people out. By default logout is disabled once people sign in through Shibboleth. Alternatively you may point logout to a url provided by your local IdP which will allow logout. If your local IdP doesn't support this and you really would like to log people out, simply create a small php script to unset the Shibboleth cookies and point people towards that, then redirect them to the standard mediawiki logout script.

Username Munging
While the extension will enforce the rule that all usernames must begin with a capital letter, it will not enforce any of the rest of mediawiki's usual rules for usernames. If your Shibboleth data will break other mediawiki username rules you should filter that out at the configuration level when $shib_UN gets set. In addition, if your shibboleth data includes sets of usernames that may only be separated by difference of upper and lower-case initial letters (Like "Nick@example.org" and "nick@example.org") then the plugin will treat these two as if they were not distinct. Again the solution is to provide additional filtering in LocalSettings.php. By default we simply use the user's e-mail addresses converting any letters to lowercase and then pass those in. (Again, the extension takes care of converting the initial letter to uppercase.)

Extension Code
<?php /** * Version 1.1.4 (Works out of box with MW 1.7 or above) * * Authentication Plugin for Shibboleth (http://shibboleth.internet2.edu) * Derived from AuthPlugin.php * Much of the commenting comes straight from AuthPlugin.php * * Portions Copyright 2006, 2007 Regents of the University of California. * Portions Copyright 2007 Steven Langenaken * Released under the GNU General Public License * * Documentation at http://meta.wikimedia.org/wiki/Shibboleth_Authentication * Project IRC Channel: #sdcolleges on irc.freenode.net * * Extension Maintainer: *        * D.J. Capelis  (Please drop me an e-mail if you'd like to help) * Extension Developers: *        * Steven Langenaken - Added assertion support, more robust https checking */

require_once('AuthPlugin.php');

class ShibAuthPlugin extends AuthPlugin { /**        * Check whether there exists a user account with the given name. * The name will be normalized to MediaWiki's requirements, so        * you might need to munge it (for instance, for lowercase initial         * letters). *        * @param string $username * @return bool * @access public */       function userExists( $username ) { return true; }       /**         * Check if a username+password pair is a valid login. * The name will be normalized to MediaWiki's requirements, so        * you might need to munge it (for instance, for lowercase initial         * letters). *        * @param string $username * @param string $password * @return bool * @access public */       function authenticate( $username, $password) { global $shib_UN; if($username == $shib_UN) return true; else return false; }

/**        * Modify options in the login template. *        * @param UserLoginTemplate $template * @access public */       function modifyUITemplate( &$template ) { $template->set( 'usedomain', false ); }

/**        * Set the domain this plugin is supposed to use when authenticating. *        * @param string $domain * @access public */       function setDomain( $domain ) { $this->domain = $domain; }

/**        * Check to see if the specific domain is a valid domain. *        * @param string $domain * @return bool * @access public */       function validDomain( $domain ) { return true; }

/**        * When a user logs in, optionally fill in preferences and such. * For instance, you might pull the email address or real name from the * external user database. *        * The User object is passed by reference so it can be modified; don't         * forget the & on your function declaration. *        * @param User $user * @access public */       function updateUser( &$user ) { global $shib_map_info; global $shib_email; global $shib_RN;

if ($shib_map_info) {                                                                                               if($shib_email != null) $user->setEmail($shib_email); if($shib_RN != null) $user->setRealName($shib_RN); }

//For security, set password to a non-existant hash. $user->load; if($user->mPassword != "nologin") {                       $user->mPassword = "nologin"; $user->saveSettings; }               return true; }

/**        * Return true if the wiki should create a new local account automatically * when asked to login a user who doesn't exist locally but does in the * external auth database. *        * If you don't automatically create accounts, you must still create * accounts in some way. It's not possible to authenticate without * a local account. *        * This is just a question, and shouldn't perform any actions. *        * @return bool * @access public */       function autoCreate { return true; }

/**        * Can users change their passwords? *        * @return bool */       function allowPasswordChange { return false; }

/**        * Set the given password in the authentication database. * Return true if successful. *        * @param string $password * @return bool * @access public */       function setPassword( $password ) { return false; }

/**        * Update user information in the external authentication database. * Return true if successful. *        * @param User $user * @return bool * @access public */       function updateExternalDB( $user ) { //Not really, but wiki thinks we did... return true; }

/**        * Check to see if external accounts can be created. * Return true if external accounts can be created. * @return bool * @access public */       function canCreateAccounts { return false; }

/**        * Add a user to the external authentication database. * Return true if successful. *        * @param User $user * @param string $password * @return bool * @access public */       function addUser( $user, $password ) { return false; }

/**        * Return true to prevent logins that don't authenticate here from being * checked against the local database's password fields. *        * This is just a question, and shouldn't perform any actions. *        * @return bool * @access public */       function strict { return false; }

/**        * When creating a user account, optionally fill in preferences and such. * For instance, you might pull the email address or real name from the * external user database. *        * The User object is passed by reference so it can be modified; don't         * forget the & on your function declaration. *        * @param User $user * @access public */       function initUser( &$user ) { $this->updateUser($user); }

/**        * If you want to munge the case of an account name before the final * check, now is your chance. */       function getCanonicalName( $username ) { return $username; } }

/* * End of AuthPlugin Code, beginning of hook code and auth functions */ function SetupShibAuth {       global $shib_UN; global $wgHooks; global $wgAuth;

if($shib_UN != null) {               $wgHooks['AutoAuthenticate'][] = 'AutoAuth'; /* Hook for magical authN */ $wgHooks['PersonalUrls'][] = 'KillLogout'; /* Disallow logout link */ $wgAuth = new ShibAuthPlugin; }       else $wgHooks['PersonalUrls'][] = 'SSOLinkAdd'; }

function SSOLinkAdd(&$personal_urls, $title) {       global $shib_WAYF, $shib_LoginHint, $shib_Https, $shib_AssertionConsumerServiceURL; if (! isset($shib_AssertionConsumerServiceURL) || $shib_AssertionConsumerServiceURL == '') $shib_AssertionConsumerServiceURL = "/Shibboleth.sso"; if (! isset($shib_Https)) $shib_Https = false; $pageurl = $title->getLocalUrl;

if (!isset($shib_LoginHint)) $shib_LoginHint = "Login via Single Sign-on";

$personal_urls['SSOlogin'] = array(               'text' => $shib_LoginHint,                'href' => ($shib_Https ? 'https' : 'http') .'://' . $_SERVER['HTTP_HOST'] .                         $shib_AssertionConsumerServiceURL . "/WAYF/" . $shib_WAYF .                        '?target=' . (isset($_SERVER['HTTPS']) ? 'https' : 'http') .                       '://' . $_SERVER['HTTP_HOST'] . $pageurl, ); }

/* Kill logout link */ function KillLogout(&$personal_urls, $title) {       global $shib_logout;

if($shib_logout == null) $personal_urls['logout'] = null; else $personal_urls['logout']['href'] = $shib_logout; }

/* Tries to be magical about when to log in users and when not to. */ function AutoAuth(&$user) {       global $wgContLang; global $wgAuth; global $shib_UN; global $wgHooks; global $shib_map_info;

//For versions of mediawiki which enjoy calling AutoAuth with null users if ($user === null) { $user = User::loadFromSession; }

//They already with us? If so, nix this function, we're good. if($user->isLoggedIn) return;

//Is the user already in the database? if (User::idFromName($shib_UN) != null) {               $user = User::newFromName($shib_UN); $smi = $shib_map_info; $shib_map_info = false; $wgAuth->updateUser($user); //Make sure password is nologin $shib_map_info = $smi; $user->SetupSession; $user->setCookies; return; }

//Okay, kick this up a notch then... $user->setName($wgContLang->ucfirst($shib_UN));

/*         * Since we only get called when someone should be logged in, if they * aren't let's make that happen. Oddly enough the way MW does all * this is simply to use a loginForm class that pretty much does * most of what you need. Creating a loginform is a very very small * part of this object. */       require_once('SpecialUserlogin.php');

//This section contains a silly hack for MW       global $wgLang; global $wgContLang; global $wgRequest; if(!isset($wgLang)) {               $wgLang = $wgContLang; $wgLangUnset = true; }

//Temporarily kill The AutoAuth Hook to prevent recursion foreach ($wgHooks['AutoAuthenticate'] as $key => $value) {               if($value == 'AutoAuth') $wgHooks['AutoAuthenticate'][$key] = 'BringBackAA'; }       //This creates our form that'll do black magic $lf = new LoginForm($wgRequest);

//Place the hook back (Not strictly necessarily MW Ver >= 1.9) BringBackAA;

//And now we clean up our hack if($wgLangUnset == true) {               unset($wgLang); unset($wgLangUnset); }

//Now we _do_ the black magic $lf->mRemember = false; $lf->initUser($user);

//Finish it off $user->saveSettings; $user->setupSession; $user->setCookies; }

/* Puts the auto-auth hook back into the hooks array */ function BringBackAA {       global $wgHooks;

foreach ($wgHooks['AutoAuthenticate'] as $key => $value) {           if($value == 'BringBackAA') $wgHooks['AutoAuthenticate'][$key] = 'AutoAuth'; } } ?>

Differences between 1.1.4 and 1.1.3

 * Security Fix: Namespace collisions are now handled by clobbering the old user
 * Cleanup for setting passwords, more compatible with new changes, less kludgy code as well
 * Fixed longstanding warning caused by a typo in an earlier version of the code (oops)

Differences between 1.1.3 and 1.1.2

 * Extra error handling plus compatibility fixes for mediawiki version 1.6.8 (hook patches added)

Differences between 1.1.2 and 1.1.1

 * Compatibilty fixes for 1.9

Differences between 1.1.1 and 1.1

 * Preserve compatibility with 1.0 configuration files for $shib_LoginHint

Differences between 1.1 and 1.0

 * Extra configuration options
 * shib_Https (whether the AssertionConsumerService url is at https, default is false)
 * shib_AssertionConsumerServiceURL (defaults to /Shibboleth.sso)
 * Sites that are accessed via https are redirected there after logging in using lazy authentication
 * Login Form Cleanup
 * New Contributor: Steven Langenaken