Extension talk:CASAuthentication

From mediawiki.org
Latest comment: 7 years ago by Menethh in topic [SOLVED] Broken in MediaWiki 1.27

Code Versioning Information[edit]

Hello,

Since I am heavily relying on this plugin on MW1.16, with a few changes to the code, I have placed it into source control on github to make it easier to maintain. It can be found here: [1]. If anyone feels like modifying it, feel free to fork and/or pull request. As long as the changes are well documented and don't break the extension for current users (ie. no need to change config to upgrade) I'll be happy to merge it.

Since the bulk of the work was done by others, and I only modified it, I tried to give credit where credit was due. Please let me know if there are any concerns over this.

Arusso (talk) 17:09, 14 March 2012 (UTC)Reply

LDAP Backend Authentication[edit]

Hello,

I've had some difficulties having your extension redirect to our cas server so I changed a condition. Moreover, we previously used ldap plugin as auth backend and would prefer to keep it active as backend (if our cas server crashed, we would need the documentation in the wiki ;-)

Here's a small patch about this :

19d18
<
33c32
< $wgHooks['UserLoginForm'][] = 'CASOverrideLoginPage';
---
> #$wgHooks['UserLoginForm'][] = 'CASOverrideLoginPage';
90,93c89,91
<
<     if (isset($_REQUEST['title'])) {
<         if ($_REQUEST['title'] == 'Special:UserLogin') {
<             # Initialise common code
---
>
>      if ( $_SESSION['wsUserName'] == NULL && $_REQUEST['title'] != 'Special:Connexion') {
>
102a101
>
107c106
<
---
>
132c131
<                       $user = $u;
---
>           $user = $u;
134,136c133,135
<          } else     if ($_REQUEST['title'] == 'Special:Userlogout') {
<             phpCAS::logout();
<         }
---
> #        } else     if ($_REQUEST['title'] == 'Special:Userlogout') {
> #            phpCAS::logout();
> #       }


Regards,

Mikael Kermorgant

Confusion Regarding Require Statements[edit]

I think you need to be more specific regarding the two conflicting require_once statements:

require_once( $IP."/extensions/CASAuth/CASAuth.php" );

vs.

require_once( $IP."/extensions/CASAuthentication/CASAuth.php" );

Also... what is this supposed to mean?

$_phpCasPath = "$IP/extensions/CASAuth/CAS";

Log-out problems[edit]

I found that log-outs were not fully successful as they left MediaWiki with a still-intact session after phpCAS::logout() was called. Making the following change to the extension causes MediaWiki to go through its full logout process and then call the casLogout() function via its UserLogoutComplete hook.

143,147c143,145
<         } else if ($_REQUEST['title'] == $lg->specialPage('Userlogout')) {
<             //needed to logout
<             phpCAS::client($_phpCASVersion,$_phpCASURL,$_phpCASPort,$_phpCASURLsub);
<             phpCAS::logout();
<         }
---
>         } else if ($_REQUEST['title'] == $lg->specialPage('Userlogout')) {
>             $user->logout();
>         }

--Adamfranco 18:59, 6 May 2009 (UTC)Reply

I have applied this fix to my wiki now. It really should be applied to Extension:CASAuthentication. --81.235.209.68 09:09, 19 July 2009 (UTC)Reply

I have now applied this to the code to the extension page. Maybe the version number and date should be updated? --81.235.209.68 11:10, 19 July 2009 (UTC)Reply




I'm using MediaWiki version 1.16 with caching completely disabled and logging out properly works only after applying this change (since the UserLogoutComplete hook doesn't get called otherwise):

SEARCH FOR:
                else if ($_REQUEST["title"] == $lg->specialPage("Userlogout")) {
                        // Logout
                        $user->logout();
                }
REPLACE WITH:
                else if ($_REQUEST["title"] == $lg->specialPage("Userlogout")) {
                        // Logout
			casLogout();
                }

SEARCH FOR:
        // Logout from MediaWiki
        $wgUser->doLogout();
REPLACE WITH:
        // Logout from MediaWiki
	$wgUser->logout();

Does that make any sense? --Hauke Pribnow 19:43, 24 May 2011 (UTC)Reply

session data[edit]

I tried using your extension and I was able to get it to half work, I found that according to phpCAS, I'm logged in however mediawiki still treats me as an anonymous user. It seems to me that there is a problem communicating the sessions data between CASphp and mediawiki, do you have any ideas on what could be causing this problem? thanks for any help that you can give redekopmark 17:59, 11 June 2009 (UTC)Reply

I am experiencing this as well. Have you managed to find the problem? --81.235.209.68 16:06, 17 July 2009 (UTC)Reply
I believe I found the solution to this. The fact that you are an anonymous user is because that user does not exist on MediaWiki. You must config CASAuth so that it can create accounts on the wiki. It makes a lot of sense if you think about it. --81.235.209.68 09:09, 19 July 2009 (UTC)Reply
I have added a note about this on the extension page. --81.235.209.68 11:10, 19 July 2009 (UTC)Reply
thanks 81.235.209.68 your awesome! redekopmark 05:20, 22 July 2009 (UTC)Reply

Cleaned and new version[edit]

Hi everyone. I have cleaned this extension, but before I edit the extension page, I want to let you know of the changes.

In the old version, the login stuff is half-broken. When the user is logged in, he still gets to the login page. The login page code is also weird, it defines some variables which are never used ($q, $linkq and $linkmsg). I don't even understand what good that login page does. In my new version, I have simply just removed the custom login page, and the login hook correctly redirects the user to the page specified by the returnto parameter.

I have also cleaned up the configuration variables to a single array, and given them better descriptions.

Fair to say, this is a much cleaner version.

If there are no objections within a few weeks, I will eventually integrate the changes into the extension page.

<?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
 * 
 * 
 * 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.1",
	"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"         => "weblogon.ltu.se",            // Address to CAS server.
	"Port"           => 443,                          // Port to CAS server. Default: 443.
	"Url"            => "/cas/",                      // 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"    => "student.ltu.se"              // The default domain for new users email address (is appended to the username).
);

//--------------------------------------------------------------------------
// CASAuth
//--------------------------------------------------------------------------

// Setup hooks
global $wgHooks;
$wgHooks["UserLoadFromSession"][] = "casLogin";
$wgHooks["UserLogoutComplete"][] = "casLogout";

// 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")) {	
			// 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"]);
			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->setOption("rememberpassword", 0);
				$u->saveSettings();
				
				// Update user count
				$ssUpdate = new SiteStatsUpdate(0,0,0,0,1);
				$ssUpdate->doUpdate();
			}
			
			// Login successful
			$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"]);
	if (isset($redirecturl)) {
		phpCAS::logoutWithRedirectServiceAndUrl($redirecturl, $redirecturl);
	}
	else {
		phpCAS::logout();
	}
	
	return true; // We won't get here
}

For the record, I was 81.235.209.68. My real name is Stefan Sundin. --81.226.241.234 17:21, 16 August 2009 (UTC)Reply

Hi, Thank you for your plugin. I get it work without any problem except that after authenticate successfully!. I close browser and try access wiki page but mediawiki still require me click on url "Log in" ( just click on url no require typing user name + password) Could this plug in do a magic that do not require us click on log in in mediawiki? Phu, —The preceding unsigned comment was added by Jonathanpham (talkcontribs) 07:23, 20 August 2009 . Please sign your posts with ~~~~!

Hi. Do you mean that the old page is cached? You could try to add t to your bookmark, it should make it certain that you don't get a cached page back. I am not sure if I do the redirect properly though. You might want to get an experienced mediawiki developer to take a look at my redirect code and ask if it can be done better. :) --93.182.181.52 12:48, 20 August 2009 (UTC)Reply

After few day I came with my local wiki & CAS everything is working well now. Strange may be cache issue Thank you so much

I am now going to incorporate the changes to the extension page now. For the record, I am 81.226.241.234, I just figure that my work on this extension isn't enough for me to create an account here. Anyway, hopefully I don't need to improve it anymore. --92.254.212.78 18:00, 5 September 2009 (UTC)Reply

Thank you for this incredibly useful extension. After the 1.1 update everything is now working like a charm. Regarding the caching issues that some folks are encountering, I was able to fix this after finding this article on disabling caching. Hope that helps. Amygreene 17:02, 12 October 2009 (UTC)Reply

Compatibility whith 1.15.3 version?[edit]

I've some problem whith this extension and the 1.15.3 version of mediawiki (It's ok with 1.15.2). Someone can me confirm if this extension is compatible with the latest stable version of mediawiki? Petit 16:15, 23 April 2010

Combining CAS with local authentication[edit]

I recently installed MediaWiki for a course project at our department, at which time a privileged user "WikiSysop" was added to the user database. Then we added CASAuth to let students and staff log in using their university accounts, leaving MediaWiki to create local users for them automatically.

Problem is, now I can't log in as "WikiSysop" to adjust any settings (or do whatever a sysop is allowed to do). All other users have been created by means of CASAuth, and none of them is in the sysop group. Before I'm logged in, the Special:UserLogin page redirects to our CAS login page, and once I'm logged in, I don't know how to switch user without logging out (sending me back to square one).

Is there any way I can have MediaWiki present me with a local login form where I can log in as "WikiSysop" (which of course is not known to CAS), or should I modify the MySQL database directly to add the sysop privilege to my CAS user instead?

I don't need the local login page to be linked from the front page, and it will only rarely be used, so a working URL is sufficient to me (or I could patch the code if I knew where to start). Since the project will only last a few months, a perfect and permanent solution is not necessary, but I'll settle for a quick and dirty fix. SM5POR 15:49, 11 June 2010 (UTC)Reply

After working around the problem by manually adding myself to the user_group database table, I found a link on the Special:SpecialPages that allowed me to log in as "WikiSysop", so my problem is essentially gone now. However, this behaviour is a bit unintuitive to me. To a non-logged-in user there are at least two different URLs with the same appearant purpose (only local paths included here):
  1. /index.php?title=Special:UserLogin&returnto=Special:SpecialPages
  2. /index.php/Special:UserLogin
Both come with the anchor text "log in / create account". The first one above appears at the top of every page, next to my IP address and "talk for this ip". This is the one which always redirects to the CAS login page. The second is found among the "Special pages", under the heading "Login / sign up", and it instead yields the local login page in MediaWiki - after first letting me log in via CAS, unless I'm already logged in.
Further testing reveals that it's the "returnto" parameter that so far has been hiding the local login page from my browser.
Now that I no longer need the local login page, I'm tempted to try to disable it instead, to avoid having regular users create additional accounts irrespective of CAS... SM5POR 14:49, 14 June 2010 (UTC)Reply

You should be able to go to Special:UserLogin after you have logged in with CAS to log in without CAS. I don't know if that is any different from using the urls you posted above. I think I'll add this to the extension page. --ReCover 00:07, 24 December 2010 (UTC)Reply

New version[edit]

Hello everyone! As I needed support for the single sign-out feature, I decided to add it to this extension. I also fixed the logout code that didn't work for me in MediaWiki version 1.15 anymore.

I'll do it like Stefan Sundin: I'll also wait for a week or two and - if there are no objections - will then update the main Extension page.

I know that the sign-out code is kinda like a hack... but IMO it's a hack you can live with. ;-)

ATTENTION: To use the new version of this extension you'll also have to add casSetup(); to your LocalSettings.php now.

Here's my new version:

<?php
/*
 * CASification script for MediaWiki 1.16 with phpCAS 1.2.1
 * 
 * Requires phpCAS: http://www.ja-sig.org/wiki/display/CASC/phpCAS
 * Install by adding these lines to LocalSetting.php:
 *  require_once("$IP/extensions/CASAuth/CASAuth.php");
 *  casSetup();
 * 
 * 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
 * 
 * 
 * Original Author: Ioannis Yessios (ioannis [dot] yessios [at] yale [dot] edu)
 * Single Sign-Out code and more: Hauke Pribnow (hauke [dot] pribnow [at] gmx [dot] de)
 * 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"     => "2.0",
        "author"      => "Ioannis Yessios, Hauke Pribnow",
        "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.
        "LogoutServers"  => false,                        // An array with hostnames that are allowed to make use of the single sign-out feature... or false to use the Server specified in the line above
        "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";

global $wgExtensionFunctions;
$wgExtensionFunctions[] = 'casLogoutCheck';

global $casIsSetUp;
$casIsSetUp = false;

// Check if there was a valid single sign-out message that terminated this session
function casLogoutCheck() {
        global $CASAuth;
	
        if(isset($_SESSION['wsCASLoggedOut']) && $_SESSION['wsCASLoggedOut']) {
                global $wgUser;
                $wgUser->logout();

                unset($_SESSION['wsCASLoggedOut']);
                unset($_SESSION['phpCAS']);
        }
}

// Login
function casLogin($user, &$result) {
        global $CASAuth;
        global $casIsSetUp;
        global $IP, $wgLanguageCode, $wgRequest, $wgOut;
 
        if (isset($_REQUEST["title"])) {
 
                $lg = Language::factory($wgLanguageCode);
 
                if ($_REQUEST["title"] == $lg->specialPage("Userlogin")) {   
                        // Setup for a web request
                        require_once("$IP/includes/WebStart.php");
 
                        // Load phpCAS
                        require_once($CASAuth["phpCAS"]."/CAS.php");
                        if(!$casIsSetUp)
                                return false;
                        
                        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
			casLogout();
                }
        }
 
        // Back to MediaWiki home after login
        return true;
}
 
// Logout
function casLogout() {
        global $CASAuth;
        global $casIsSetUp;
        global $wgUser, $wgRequest, $wgLanguageCode;

	require_once($CASAuth["phpCAS"]."/CAS.php");
	
        // Logout from MediaWiki
	$wgUser->logout();
 
        // Get returnto value
        $returnto = $wgRequest->getVal("returnto");
        if ($returnto) {
                $lg = Language::factory($wgLanguageCode);
                $target = Title::newFromText($returnto);
                if ($target && $target->getPrefixedDBkey() != $lg->specialPage("Userlogout")) {
                        $redirecturl = $target->getFullUrl();
                }
        }
 
        if(!$casIsSetUp)
                return false;

        // Logout from CAS (will redirect user to CAS server)
        
        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;
}

// Store the session name and id in a new logout ticket session to be able
// to find it again when single signing-out
function casPostAuth($ticket2logout) {

        // remember the current session name and id
        $old_session_name=session_name();
        $old_session_id=session_id();

        // close the current session for now
        session_write_close();
        session_unset();
        session_destroy();

        // create a new session where we'll store the old session data
        session_name("casauthssoutticket");
        session_id(preg_replace('/[^\w]/','',$ticket2logout));
        session_start();

        $_SESSION["old_session_name"] = $old_session_name;
        $_SESSION["old_session_id"] = $old_session_id;

        // close the ssout session again
        session_write_close();
        session_unset();
        session_destroy();

        // and open the old session again
        session_name($old_session_name);
        session_id($old_session_id);
        session_start();
}

// The CAS server sent a single sign-out command... let's process it
function casSingleSignOut($ticket2logout) {
        global $CASAuth;
        global $IP;

        require_once($CASAuth["phpCAS"]."/CAS.php");

        $session_id = preg_replace('/[^\w]/','',$ticket2logout);

        // destroy a possible application session created before phpcas
        if(session_id() !== ""){
                session_unset();
                session_destroy();
        }

        // load the ssout session
        session_name("casauthssoutticket");
        session_id($session_id);
        session_start();

        // extract the user session data
        $old_session_name = $_SESSION["old_session_name"];
        $old_session_id = $_SESSION["old_session_id"];

        // close the ssout session again
        session_unset();
        session_destroy();

        // load the user session
        session_name($old_session_name);
        session_id($old_session_id);
        session_start();

        // set the flag that the user session is to be closed
        $_SESSION['wsCASLoggedOut'] = true;

        // close the user session again
        session_write_close();
        session_unset();
        session_destroy();
}

function casSetup() {
        global $CASAuth;
        global $casIsSetUp;
        
        require_once($CASAuth["phpCAS"]."/CAS.php");
        phpCAS::client($CASAuth["Version"], $CASAuth["Server"], $CASAuth["Port"], $CASAuth["Url"], false);
        phpCAS::setSingleSignoutCallback('casSingleSignOut');
        phpCAS::setPostAuthenticateCallback('casPostAuth');
        phpCAS::handleLogoutRequests(true,isset($CASAuth["LogoutServers"])?$CASAuth["LogoutServers"]:false);
        phpCAS::setNoCasServerValidation();
	
        $casIsSetUp = true;
}

--109.91.124.223 13:16, 27 May 2011 (UTC)Reply

Whoops... and that happens when you're not logged in. The code above was posted by me. --Hauke Pribnow 13:17, 27 May 2011 (UTC)Reply

CAS Authentication w/User Filtering[edit]

I needed the ability to restrict who could login, as we want to use this for CAS Auth, but we dont want everyone logging in, just a select few. To make things simple, I just add another CASAuth variable to hold the Allowed Users, and then check to see if our CAS authenticated username returns one of such users.

So building on Stefan's version, I added the following to the CASAuth array in CASAuth.php:

$CASAuth = array(                                                                                                                    
       // ...                                                                   
       "AllowedUsers"   => false,                        // Array of allowed users                                                                     
       // ...
);

And then below, I added:


...

 // Get username                                                                                                                 
$username = phpCAS::getUser();

// Verify they have access to the Team Wiki                                                                                     
require_once("$IP/extensions/CASAuth/users.php");
if(!in_array($username,$CASAuth["AllowedUsers"]))
  {
    # redirect user to some other page                                                                                            
    $wgOut->redirect('http://www.berkeley.edu');
    return true;
  }

// Get MediaWiki user                                                                                                           
$u = User::newFromName($username);

...

Finally, the contents of the users.php:

<?php

# only enable the below line immediately after adding a user, and verifying they can login
# otherwise, this should be set to false (or commented out) to maintain additional security.
# make sure this is set to false in CASAuth.php as well!!!
#$CASAuth["CreateAccounts"]=true;

# Below are the valid users who can login to the wiki
# $CASAuth["AllowedUsers"[] = '######';
$CASAuth["AllowedUsers"][] = 'username'; # username should be a valid CAS returned username

Bypass CAS login with "Local Login" link[edit]

Here's a patch to allow local database authenticated logins without first requiring a CAS login.

diff --git a/CASAuth.php b/CASAuth.php
index a33c49c..3abd303 100644
--- a/CASAuth.php
+++ b/CASAuth.php
@@ -57,12 +57,14 @@ $wgHooks["GetPreferences"][] = "casPrefs";
 function casLogin($user, &$result) {
         global $CASAuth;
         global $IP, $wgLanguageCode, $wgRequest, $wgOut;
+
+               $bypass_cas = $wgRequest->getVal('local', false);
  
         if (isset($_REQUEST["title"])) {
  
                 $lg = Language::factory($wgLanguageCode);
  
-                if ($_REQUEST["title"] == $lg->specialPage("Userlogin")) {      
+                if ($_REQUEST["title"] == $lg->specialPage("Userlogin") && ! $bypass_cas) {      
                         // Initialize the session
                         session_start();

The URL to use would be like this (replace $wiki_url with appropriate path for accessing your wiki)

$wiki_url/Special:UserLogin?local=true

Token cookie for elongated sessions[edit]

An issue I've noticed on my forked version of this extension is that users have a tendency to get logged out within a few hours.

After spending much too long trying to debug it, I finally figured out the cause: no "Token" cookie was created. This cookie is briefly described in the setCookies method documentation.

Luckily the fix was very simple, and I've applied it to the code on this extension's page; people using it in the future should no longer experience the problem I did.

I changed the line "$u->setCookies();" to "$u->setCookies(null, null, $CASAuth["RememberMe"]);"; the third parameter being whether to create a Token cookie. Menethh (talk) 21:27, 2 November 2015 (UTC)Reply

[SOLVED] Broken in MediaWiki 1.27[edit]

With MediaWiki 1.27, there were major overhauls to both session management and authentication (see Release_notes/1.27). In particular, PHP session handling is deprecated, so this extension's use of variables like $_SESSION and $session_id is broken. Further, several hooks used by this extension are now deprecated. The new SessionManager and AuthManager frameworks were implemented to replace this functionality (see Manual:SessionManager and AuthManager).

These changes appear to be have broken Extension:CASAuthentication. Has anyone looked into this issue?

--Jpgill86 (talk) 22:33, 9 August 2016 (UTC)Reply

[UPDATE]

I took it upon myself to get this working with MediaWiki 1.27. I forked Arusso's version on GitHub, incorporated several of the improvements made by others who had done the same, and made minimal changes to get the extension working again. I believe I was able to preserve backwards compatibility, as I also tested it in MW 1.23, and it seems to work fine in both environments (although, if you are using it in MW 1.27, you must remove casSetup() from your LocalSettings.php).

My fork of the extension is available here: https://github.com/CWRUChielLab/CASAuth

I was able to get the extension working with MW 1.27 without overhauling it to use the new SessionManager and AuthManager. For now, it is surviving by utilizing the same old means of accessing session data through $_SESSION. In some future release of MW, I imagine use of SessionManager and AuthManager could become mandatory, which will certainly break the extension in its current form. I believe the right way to handle this would be to create a class that extends MediaWiki\Auth\AbstractPrimaryAuthenticationProvider, much like is done in Extension:GoogleLogin. That can be someone else's problem one day!

--Jpgill86 (talk) 23:00, 20 August 2016 (UTC)Reply

I've marked the extension as incompatible and unmaintained. Not sure what the protocol is, but it seems to me like it'd be best to replace the extension with your version, considering yours actually works with 1.27. Menethh (talk) 23:09, 12 September 2016 (UTC)Reply