WordPress.org

Ready to get started?Download WordPress

Forums

Problem of authentication when loggin through SimpleSAML on wordpress MU (5 posts)

  1. Tatichka
    Member
    Posted 1 year ago #

    Hello,

    I work for a quite big company and I have to migrate our previous wordpress MU to WP MU 3.5. I also need to use the simplesaml plugin to authenticate our users through our LDAP.

    However, I had to change a few things on the simplesaml plugin 0.6.4, I pasted the whole plugin below.

    <?php
    /*
    Plugin Name: simpleSAMLphp for Oxylane with role management
    Version: 0.5.1
    Plugin URI: http://grid.ie/wiki/WordPress_simpleSAMLphp_authentication
    Description: Authenticate users using <a href="http://rnd.feide.no/simplesamlphp">simpleSAMLphp</a>. This modified version allows to work with WordPress Network for the Oxylanes' needs.
    Author: David O'Callaghan modified by Vincent Vatelot
    Author URI: http://www.cs.tcd.ie/David.OCallaghan/
    */
    
    /* Copyright (C) 2009 David O'Callaghan (david.ocallaghan {} cs <> tcd <> ie)
    
     This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
     the Free Software Foundation; either version 2 of the License, or
     (at your option) any later version.
    
     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.
    
     You should have received a copy of the GNU General Public License
     along with this program; if not, write to the Free Software
     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
    
    add_action('network_admin_menu', 'simplesaml_authentication_add_options_page');
    add_action('admin_menu', 'simplesaml_authentication_add_options_page');
    
    $simplesaml_authentication_opt = get_site_option('simplesaml_authentication_options');
    
    $simplesaml_configured = true;
    
    // try to configure the simpleSAMLphp client
    if ($simplesaml_authentication_opt['include_path'] == '') {
    
      $simplesaml_configured = false;
    } else {
      $include_file = $simplesaml_authentication_opt['include_path']."/lib/_autoload.php";
      if (!include_once($include_file))
        $simplesaml_configured = false;
    }
    
    if ($simplesaml_configured) {
      if($simplesaml_authentication_opt['sp_auth'] == '')
        $sp_auth = 'default-sp';
      else
        $sp_auth = $simplesaml_authentication_opt['sp_auth'];
      $as = new SimpleSAML_Auth_Simple($sp_auth);
    }
    
    // for wp_create_user function on line 120
    require_once (ABSPATH . WPINC . '/registration.php');
    
    // plugin hooks into authentication system
    add_action('wp_authenticate', array('SimpleSAMLAuthentication', 'authenticate'), 10, 2);
    add_action('wp_logout', array('SimpleSAMLAuthentication', 'logout'));
    add_action('lost_password', array('SimpleSAMLAuthentication', 'disable_function'));
    add_action('retrieve_password', array('SimpleSAMLAuthentication', 'disable_function'));
    add_action('password_reset', array('SimpleSAMLAuthentication', 'disable_function'));
    add_filter('show_password_fields', array('SimpleSAMLAuthentication', 'show_password_fields'));
    add_filter('init', array('SimpleSAMLAuthentication','check_auth_to_read'));
    add_filter('login_url', array('SimpleSAMLAuthentication','disable_reauth')); //removes reauth from login URL
    
    $slo = $simplesaml_authentication_opt['slo'];
    
    if ($slo) {
    
    	/* Logout the user from wp if not exists an authenticated session at the simplesamlphp SP
    	 This function overrides the is_logged_in function from wp core.
    	 (Other solution could be to extend the wp_validate_auth_cookie func instead)
    	*/
    	function is_user_logged_in() {
    		global $as;
    
    		$user = wp_get_current_user();
    		if ( $user->id > 0 ) {
    			// User is local authenticated but SP session was closed
    			if (!isset($as)) {
    				global $simplesaml_authentication_opt;
    				$sp_auth = ($simplesaml_authentication_opt['sp_auth'] == '') ? 'default-sp' : $simplesaml_authentication_opt['sp_auth'];
    				$as = new SimpleSAML_Auth_Simple($sp_auth);
    			}
    
    			if(!$as->isAuthenticated()) {
    				wp_logout();
    				return false;
    			} else {
    				return true;
    			}
    		}
    		return false;
    	}
    }
    
    if (!class_exists('SimpleSAMLAuthentication')) {
      class SimpleSAMLAuthentication {
    
    	    public static function check_auth_to_read () {
    			global $simplesaml_authentication_opt, $simplesaml_configured, $as, $wpdb;
    			$secure_blog = $simplesaml_authentication_opt['secure_blog'];
    
         		if ($secure_blog) {
    				//force authentication
    				$as->requireAuth();
    				$attributes = $as->getAttributes();
    				$username = $attributes['uid'][0];
    			  $user = get_userdatabylogin($username);
    			$user_id = $user->ID;
    				wp_set_current_user($user_id);
    				wp_set_auth_cookie($user_id,true);
    
    				//do_action('wp_login', $user_id);
    
    				/*$username = $attributes['uid'][0];
    				$creds = array();
    				$creds['user_login'] = $username;
    				$creds['user_password'] = 'plaintext';
    				$creds['remember'] = true;
    				$user = wp_signon( $creds, false);
    				//wp_set_auth_cookie($user->ID);
    			if ( is_wp_error($user) ){
    					//var_dump $user->get_error_message();
    					}*/
    				if (!is_user_logged_in() ) {
    					auth_redirect();
    				}
    			}
    		}
        // password used by the plugin
        function passwordRoot() {
          return 'Authenticated through SimpleSAML';
        }    
    
        /*
         We call simpleSAMLphp to authenticate the user at the appropriate time
         If the user has not logged in previously, we create an account for them
        */
        function authenticate(&$username, &$password) {
          global $simplesaml_authentication_opt, $simplesaml_configured, $as, $blog_id;
    
          if (!$simplesaml_configured)
            die("simplesaml-authentication plugin not configured");
    
          // Reset values from input ($_POST and $_COOKIE)
          $username = $password = '';
          $as->requireAuth();
    
          $attributes = $as->getAttributes();
          $username = $attributes['uid'][0];
          $username = strtolower($username);
          $password = md5(SimpleSAMLAuthentication::passwordRoot());
          if (!function_exists('get_userdatabylogin'))
            die("Could not load user data");
          $user = get_userdatabylogin($username);
    	$user_id = $user->ID;
    	$lastname = $attributes['sn'][0];
    	$contracttype = $attributes['contracttype'][0];
    	$subsidiary = $attributes['subsidiary'][0];
    	$firstname = $attributes['givenname'][0];
    	$email = $attributes['mail'][0];
    
    //Vérifier si le user existe dans la base globale:
         if ($user) {
            // Le user existe bien dans la base globalle
    	// On vérifie si le user existe pour le blog concerné
    	if (is_user_member_of_blog($user_id)) {
    	      	//user is a member of this blog
    		//On met à jour son nom, prenom et son mail...
    		update_user_meta($user_id, 'last_name', $lastname);
    		update_user_meta($user_id, 'first_name', $firstname);
    		update_user_meta($user_id, 'contract_type', $contracttype);
    		update_user_meta($user_id, 'subsidiary', $subsidiary);
    
    		wp_update_user( array ('ID' => $user_id, 'user_email' => $email, 'user_pass' => $password) ) ;
    		wp_set_current_user($user_id);
    		return true;
       	} else {
    		// Le user n'existe pas pour ce blog, on va donc le créer...
    		$blog_id = get_current_blog_id();
    		$user_id = $user->ID;
    		$new_role = "subscriber";
    	        add_user_to_blog($blog_id, $user_id, $new_role);
                    //On met à jour son nom, prenom et son mail...
                    update_user_meta($user_id, 'last_name', $lastname);
                    update_user_meta($user_id, 'first_name', $firstname);
    				update_user_meta($user_id, 'contract_type', $contracttype);
    				update_user_meta($user_id, 'subsidiary', $subsidiary);
                    wp_update_user( array ('ID' => $user_id, 'user_email' => $email, 'user_pass' => $password) ) ;
    				wp_set_current_user($user_id);
    		return true;
    	}
          } else {
    		// first time logging in
            if ($simplesaml_authentication_opt['new_user'] == 1) {
              // auto-registration is enabled
              // User is not in the WordPress database
              // they passed SimpleSAML and so are authorized
              // add them to the global user database and local blog database
              // User must have an email address to register
    
              $user_email = '';
    
              if($attributes['mail']) {
                // Try to get email address from attributes
                $user_email = $attributes['mail'][0];
              } else {
                // Otherwise use default email suffix
                if ($simplesaml_authentication_opt['email_suffix'] != '')
                  $user_email = $username . '@' . $simplesaml_authentication_opt['email_suffix'];
              }
    
              $user_info = array();
              $user_info['user_login'] = $username;
              $user_info['user_pass'] = $password;
              $user_info['user_email'] = $user_email;
    
              if($attributes['givenName'])
                $user_info['first_name'] = $attributes['givenName'][0];
              if($attributes['sn'])
                $user_info['last_name'] = $attributes['sn'][0];
              if($attributes['cn'])
                $user_info['name'] = $attributes['cn'][0];
    
              // Set user role based on eduPersonEntitlement
              if($simplesaml_authentication_opt['admin_entitlement'] != '' &&
    	     $attributes['eduPersonEntitlement'] && in_array($simplesaml_authentication_opt['admin_entitlement'], $attributes['eduPersonEntitlement'])) {
                $user_info['role'] = "administrator";
              } else {
                $user_info['role'] = "subscriber";
              }
            $wp_uid = wpmu_create_user($username, $password, $user_email);
            $blog_id = get_current_blog_id();
            $new_role = "subscriber";
            add_user_to_blog($blog_id, $wp_uid, $new_role);
            //On met à jour son nom, prenom et son mail...
            update_user_meta($wp_uid, 'last_name', $lastname);
            update_user_meta($wp_uid, 'first_name', $firstname);
    		update_user_meta($wp_uid, 'contract_type', $contracttype);
    		update_user_meta($wp_uid, 'sale_channel', $channel);
            wp_update_user( array ('ID' => $wp_uid, 'user_email' => $email, 'user_pass' => $password) ) ;
    		wp_set_current_user($wp_uid);
    	return true;
            }
    
            else {
              $error = sprintf(__('<p><strong>ERROR</strong>: %s is not registered with this blog. Please contact the <a href="mailto:%s">blog administrator</a> to create a new account!</p>'), $username, get_option('admin_email'));
              $errors['registerfail'] = $error;
              print($error);
              print('<p><a href="/wp-login.php?action=logout">Log out</a> of SimpleSAML.</p>');
              exit();
            }
          }
    
        }
    
    /*
    when in SSO mode we don.t need to forse a relog in so theis stops that
    */
    function disable_reauth($login_url){
            //die($login_url);
    		//return str_replace($login_url,$_SERVER['PHP_SELF'].'/wp-admin',$login_url);
    		return str_replace('&reauth=1','',$login_url);
    }
    
        function logout() {
          global $simplesaml_authentication_opt, $simplesaml_configured, $as;
          if (!$simplesaml_configured)
            die("simplesaml-authentication not configured");
    
          $as->logout(get_settings('siteurl'));
        }
    
        /*
         Don't show password fields on user profile page.
        */
        function show_password_fields($show_password_fields) {
          return false;
        }
    
        function disable_function() {
          die('Disabled');
        }
    
      }
     }
    
    //----------------------------------------------------------------------------
    //		ADMIN OPTION PAGE FUNCTIONS
    //----------------------------------------------------------------------------
    
    function simplesaml_authentication_add_options_page() {
            if (function_exists('add_submenu_page')) {
                    // does not use add_options_page, because it is site-wide configuration,
                    //  not blog-specific config, but side-wide
                    add_submenu_page('settings.php', 'SimpleSAML config', 'SimpleSAML', '', basename(__FILE__), 'simplesaml_authentication_options_page');
      }
    } 
    
    function simplesaml_authentication_options_page() {
      global $wpdb;
    
      // Setup Default Options Array
      $optionarray_def = array(
    			   'new_user' => FALSE,
    			   'slo' => FALSE,
    			   'redirect_url' => '',
    			   'email_suffix' => 'example.com',
    			   'sp_auth' => 'default-sp',
    			   'include_path' => '/var/simplesamlphp',
    			   'admin_entitlement' => '',
    			   'secure_blog' => '',
    			   );
    
      if (isset($_POST['submit']) ) {
        // Options Array Update
        $optionarray_update = array (
    				 'new_user' => $_POST['new_user'],
    				 'slo' => $_POST['slo'],
    				 'email_suffix' => $_POST['email_suffix'],
    				 'include_path' => $_POST['include_path'],
    				 'sp_auth' => $_POST['sp_auth'],
    				 'admin_entitlement' => $_POST['admin_entitlement'],
    				 'secure_blog' => $_POST['secure_blog'],
    				 );
    
        update_site_option('simplesaml_authentication_options', $optionarray_update);
      }
    
      // Get Options
      $optionarray_def = get_site_option('simplesaml_authentication_options');
    
      ?>
    	<div class="wrap">
    	<h2>simpleSAMLphp Authentication Options</h2>
    	<form method="post" action="<?php echo $_SERVER['PHP_SELF'] . '?page=' . basename(__FILE__); ?>&updated=true">
    	<fieldset class="options">
    
         <h3>User registration options</h3>
    
    	<table class="form-table">
    	   <tr valign="top">
    		<th scope="row">User registration</th>
    		<td><label for="new_user">
    		<input name="new_user" type="checkbox" id="new_user_inp" value="1" <?php checked('1', $optionarray_def['new_user']); ?> />
    Automatically register new users</label>
    		<span class="setting-description">(Users will be registered with the role of Subscriber.)</span></td>
    		</tr>
    <!--		<tr>
    		<th><label for="email_suffix"> Default email domain</label></th>
    		<td>
    	   	<input type="text" name="email_suffix" id="email_suffix_inp" value="<?php echo $optionarray_def['email_suffix']; ?>" size="35" />
    		<span class="setting-description">If an email address is not availble from the <acronym title="Identity Provider">IdP</acronym> <strong>username@domain</strong> will be used.</td>
    </tr>-->
    		<tr>
    		<th> <label for="admin_entitlement">Administrator Entitlement URI</label></th>
    		<td>
    		<input type="text" name="admin_entitlement" id="admin_entitlement_inp" value="<?php echo $optionarray_def['admin_entitlement']; ?>" size="40" />
    		<span class="setting-description">An <a href="http://rnd.feide.no/node/1022">eduPersonEntitlement</a> URI to be mapped to the Administrator role.</span>
    		</td>
    		</tr>
    	</table>
    
        <h3>simpleSAMLphp options</h3>
        <p><em>Note:</em> Once you fill in these options, WordPress authentication will happen through <a href="http://rnd.feide.no/simplesamlphp">simpleSAMLphp</a>, even if you misconfigure it. To avoid being locked out of WordPress, use a second browser to check your settings before you end this session as Administrator. If you get an error in the other browser, correct your settings here. If you can not resolve the issue, disable this plug-in.</p>
    
    	<table class="form-table">
    	   <tr valign="top">
    		<th scope="row"><label for="include_path">Path to simpleSAMLphp</label></th>
    		<td><input type="text" name="include_path" id="include_path_inp" value="<?php echo $optionarray_def['include_path']; ?>" size="35" />
    		<span class="setting-description">simpleSAMLphp suggested location is <tt>/var/simplesamlphp</tt>.</span>
    		</td>
    		</tr>
    
    	   <tr valign="top">
    	   <th scope="row"><label for="sp_auth">Authentication source ID</label></th>
    	   <td><input type="text" name="sp_auth" id="sp_auth_inp" value="<?php echo $optionarray_def['sp_auth']; ?>" size="35" />
    		<span class="setting-description">simpleSAMLphp default is "default-sp".</span>
                 </td>
    	     </tr>
    	<tr valign="top">
    		<th scope="row"><label for="slo">Single Log Out</label></th>
    		<td><input type="checkbox" name="slo" id="slo" value="1" <?php checked('1', $optionarray_def['slo']); ?> />
    		<span class="setting-description">Enable Single Log out</span>
    		</td>
    	</tr>
    	<tr valign="top">
    		<th scope="row"><label for="secure_blog">Secure Blog</label></th>
    		<td><input type="checkbox" name="secure_blog" id="secure_blog" value="1" <?php checked('1', $optionarray_def['secure_blog']); ?> />
    		<span class="setting-description">Enable Secure Blog</span>
    		</td>
    	</tr>
    	</table>
    	</fieldset>
    	<p />
    	<div class="submit">
    		<input type="submit" name="submit" value="<?php _e('Update Options') ?> &raquo;" />
    	</div>
    	</form>
    <?php
    }
    ?>

    The problem is, whenever I tried to login as a normal user to the dashboard of one of the blogs through our Identity provider, I am correctly logged in (I can see the WP cookies are created), but I still get redirected to http://mywordpressmu/wordpress/wp-login.php?redirect_to=http%3A%2F%2Fmywordpressmu%2Fwordpress%2Fwp-admin%2F
    But if I remove the wp-login.php?redirect_to=http%3A%2F%2Fmywordpressmu%2Fwordpress%2Fwp-admin%2F and replace it by wp-admin, I can access the dashboard.

    Another thing is, when I try to do the same thing as a super admin I get correctly redirected and logged in to the dashboard, without replacing the URL.

    My first guess was that the cookies weren't created, but I can see them being created when I log in. Second guess is that the wp-login.php behaves differently and redirect correctly when super admin, but it's not the case when I log in as a normal user.

    Any ideas on how I should proceed? I don't want to change anything on wp-login.php, so I am guessing it's the way I WP authenticate the users that is wrong.

    FYI, I tried the wp_signon function, as follow
    ` $username = $attributes['uid'][0];
    $creds = array();
    $creds['user_login'] = $username;
    $creds['user_password'] = 'plaintext';
    $creds['remember'] = true;
    $user = wp_signon( $creds, false);
    //wp_set_auth_cookie($user->ID);
    if ( is_wp_error($user) ){
    //var_dump $user->get_error_message();
    }
    but it doesn't work.

    Please help!

  2. Tatichka
    Member
    Posted 1 year ago #

    Another thing is when I log through simplesaml to access a blog page (I enabled secure blog so that I secure not only the admin but the whole blog), WP seems to recognize im logged in since I can see the task bar at the top of the window..
    I'm still looking in the cookies and wp-login.php, but till now no luck..

  3. Tatichka
    Member
    Posted 1 year ago #

    Nevermind, I cleared my cookies and something else happened. Once I finished loggin in through simplesaml, I can access the page right, but don't see the tasks bar. If I refresh the page though, it appears.. so I'm thinking cookie validation?

  4. Try putting this in your wp-config

    define('ADMIN_COOKIE_PATH', '/');
    define('COOKIE_DOMAIN', '');
    define('COOKIEPATH', '');
    define('SITECOOKIEPATH', '');
  5. Tatichka
    Member
    Posted 1 year ago #

    I already tried it didn't change anything..
    I'm going to install the simplesaml plugin again on a wordpress 3.5 without multisites and see if I have the same result.
    I will keep you posted on that.

Topic Closed

This topic has been closed to new replies.

About this Topic