Skip to content
Yi-Pu Guo edited this page Jun 20, 2013 · 18 revisions

Category:Library::Community | Category:Library::OpenID

Getting started:

Download the following files:

Complete 'How To' get this working:

http://thinkmoult.com/2009/02/22/use-codeigniter-openid-library-to-integrate-openid/

User information not working from Google?

You will need to augment your code with OpenID AX support: http://stackoverflow.com/questions/1183788/example-usage-of-ax-in-php-openid

Source:

(from File:OpenID-Library.zip)

libraries/Openid.php

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* OpenID Library
*
* @package    CodeIgniter
* @author     bardelot
* @see        http://cakebaker.42dh.com/2007/01/11/cakephp-and-openid/
*             & http://openidenabled.com/php-openid/
*/

class Openid{

  var $storePath = 'tmp';
  
  var $sreg_enable = false;
  var $sreg_required = null;
  var $sreg_optional = null;
  var $sreg_policy = null;
  
  var $pape_enable = false;
  var $pape_policy_uris = null;
  
  var $request_to;
  var $trust_root;
  var $ext_args;
    
    function Openid()
    {        
    $CI =& get_instance();    
        $CI->config->load('openid');
        $this->storePath = $CI->config->item('openid_storepath');
            
        session_start();    
        $this->_doIncludes();
            
    log_message('debug', "OpenID Class Initialized");
    }
    
    function _doIncludes()
    {
    set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path());

    require_once "Auth/OpenID/Consumer.php";
    require_once "Auth/OpenID/FileStore.php";
    require_once "Auth/OpenID/SReg.php";
    require_once "Auth/OpenID/PAPE.php";
  }
    
    function set_sreg($enable, $required = null, $optional = null, $policy = null)
    {
    $this->sreg_enable = $enable;
    $this->sreg_required = $required;
    $this->sreg_optional = $optional;
    $this->sreg_policy = $policy;
    }
    
    function set_pape($enable, $policy_uris = null)
    {
    $this->pape_enable = $enable;
    $this->pape_policy_uris = $policy_uris;
    }
    
    function set_request_to($uri)
    {
    $this->request_to = $uri;
    }
    
    function set_trust_root($trust_root)
    {
    $this->trust_root = $trust_root;
    }
    
    function set_args($args)
    {
    $this->ext_args = $args;
    }
    
    function _set_message($error, $msg, $val = '', $sub = '%s')
    {
      $CI =& get_instance();
        $CI->lang->load('openid', 'english');
        echo str_replace($sub, $val, $CI->lang->line($msg));
        
        if ($error)
        {
      exit;
    }
    }
    
    function authenticate($openId)
    {
    $consumer = $this->_getConsumer();
        $authRequest = $consumer->begin($openId);
            
        // No auth request means we can't begin OpenID.
    if (!$authRequest)
    {
        $this->_set_message(true,'openid_auth_error');
    }
      
    if ($this->sreg_enable)
    {
        $sreg_request = Auth_OpenID_SRegRequest::build($this->sreg_required, $this->sreg_optional, $this->sreg_policy);

        if ($sreg_request)
        {
            $authRequest->addExtension($sreg_request);
        }
        else
        {
            $this->_set_message(true,'openid_sreg_failed');
        }
    }
      
    if ($this->pape_enable)
    {
        $pape_request = new Auth_OpenID_PAPE_Request($this->pape_policy_uris);
        
        if ($pape_request)
        {
            $authRequest->addExtension($pape_request);
        }
        else
        {
            $this->_set_message(true,'openid_pape_failed');
        }
    }
            
        if ($this->ext_args != null)
        {
                foreach ($this->ext_args as $extensionArgument)
                {
            if (count($extensionArgument) == 3)
            {
                 $authRequest->addExtensionArg($extensionArgument[0], $extensionArgument[1], $extensionArgument[2]);
            }
                }
    }
            
        // Redirect the user to the OpenID server for authentication.
    // Store the token for this authentication so we can verify the
    // response.

    // For OpenID 1, send a redirect.  For OpenID 2, use a Javascript
    // form to send a POST request to the server.
    if ($authRequest->shouldSendRedirect())
    {
        $redirect_url = $authRequest->redirectURL($this->trust_root, $this->request_to);

        // If the redirect URL can't be built, display an error
        // message.
        if (Auth_OpenID::isFailure($redirect_url))
        {
            $this->_set_message(true,'openid_redirect_failed', $redirect_url->message);
        }
        else
        {
            // Send redirect.
            header("Location: ".$redirect_url);
        }
    }
    else
    {
        // Generate form markup and render it.
        $form_id = 'openid_message';
        $form_html = $authRequest->formMarkup($this->trust_root, $this->request_to, false, array('id' => $form_id));

        // Display an error if the form markup couldn't be generated;
        // otherwise, render the HTML.
        if (Auth_OpenID::isFailure($form_html))
        {
            $this->_set_message(true,'openid_redirect_failed', $form_html->message);
        }
        else
        {
            $page_contents = array(
               "<html><head><title>",
               "OpenID transaction in progress",
               "</title></head>",
               "<body onload='document.getElementById(\"".$form_id."\").submit()'>",
               $form_html,
               "</body></html>");

            print implode("\n", $page_contents);
        }
    }

        }
        
        function getResponse()
        {
      $consumer = $this->_getConsumer();
      $response = $consumer->complete($this->request_to);
            
      return $response;
        }
        
        function _getConsumer()
        {
            if (!file_exists($this->storePath) && !mkdir($this->storePath))
            {
          $this->_set_message(true,'openid_storepath_failed', $this->storePath);
            }

            $store = new Auth_OpenID_FileStore($this->storePath);
            $consumer = new Auth_OpenID_Consumer($store);
            
            return $consumer;
        }
}
?>

config/openid.php

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

$config['openid_storepath'] = 'tmp';
$config['openid_policy'] = 'test/policy';
$config['openid_required'] = array('nickname');
$config['openid_optional'] = array('fullname', 'email');
$config['openid_request_to'] = 'test/check';

?>

language/english/openid_lang.php

<?php

$lang['openid_cancel'] = "Verification cancelled.";
$lang['openid_failure'] = "OpenID authentication failed: %s";
$lang['openid_success'] = 'You have successfully verified <a href="%s">%t</a> as your identity.';
$lang['openid_pape_policies_affected'] = "<p>The following PAPE policies affected the authentication:</p><ul>";
$lang['openid_pape_noresponse'] = "<p>No PAPE response was sent by the provider.</p>";
$lang['openid_pape_not_affected'] = "<p>No PAPE policies affected the authentication.</p>";
$lang['openid_content'] = " Your %s is '%t'.";
$lang['openid_canonical'] = "  (XRI CanonicalID: %s) ";
$lang['openid_nist_level'] = "<p>The NIST auth level returned by the server is: <tt>%s</tt></p>";
$lang['openid_auth_age'] = "<p>The authentication age returned by the server is: <tt>%s</tt></p>";

$lang['openid_auth_error'] = 'Authentication error; not a valid OpenID.';
$lang['openid_sreg_failed'] = 'SREG failed.';
$lang['openid_pape_failed'] = 'PAPE failed.';
$lang['openid_redirect_failed'] = 'Could not redirect to server: %s';
$lang['openid_storepath_failed'] = 'Could not create the FileStore directory %s. Please check the effective permissions.';

?&gt;

controller/test.php

&lt;?php

class Test extends Controller {

    function Test()
    {
        parent::Controller();

    $this->lang->load('openid', 'english');
        $this->load->library('openid');
        $this->load->helper('url');
        //$this->output->enable_profiler(TRUE);
    }
    
    // Index
    function index()
    {
    if ($this->input->post('action') == 'verify')
    {
        $user_id = $this->input->post('openid_identifier');
        $pape_policy_uris = $this->input->post('policies');
        
        if (!$pape_policy_uris)
        {
          $pape_policy_uris = array();
        }
        
        $this->config->load('openid');      
        $req = $this->config->item('openid_required');
        $opt = $this->config->item('openid_optional');
        $policy = site_url($this->config->item('openid_policy'));
        $request_to = site_url($this->config->item('openid_request_to'));
        
        $this->openid->set_request_to($request_to);
        $this->openid->set_trust_root(base_url());
        $this->openid->set_args(null);
        $this->openid->set_sreg(true, $req, $opt, $policy);
        $this->openid->set_pape(true, $pape_policy_uris);
        $this->openid->authenticate($user_id);
    } 
    
    $data['pape_policy_uris'] = array(
        PAPE_AUTH_MULTI_FACTOR_PHYSICAL,
        PAPE_AUTH_MULTI_FACTOR,
        PAPE_AUTH_PHISHING_RESISTANT
        );
        
    $this->load->view('view_openid', $data);

    }
    
    // Policy
    function policy()
    {
      $this->load->view('view_policy');
    }
    
    // set message
    function _set_message($msg, $val = '', $sub = '%s')
    {
        return str_replace($sub, $val, $this->lang->line($msg));
    }
    
    // Check
    function check()
    {    
      $this->config->load('openid');
      $request_to = site_url($this->config->item('openid_request_to'));
      
      $this->openid->set_request_to($request_to);
    $response = $this->openid->getResponse();

    switch ($response->status)
    {
        case Auth_OpenID_CANCEL:
            $data['msg'] = $this->lang->line('openid_cancel');
            break;
        case Auth_OpenID_FAILURE:
            $data['error'] = $this->_set_message('openid_failure', $response->message);
            break;
        case Auth_OpenID_SUCCESS:
            $openid = $response->getDisplayIdentifier();
            $esc_identity = htmlspecialchars($openid, ENT_QUOTES);

            $data['success'] = $this->_set_message('openid_success', array($esc_identity, $esc_identity), array('%s','%t'));

            if ($response->endpoint->canonicalID) {
                $data['success'] .= $this->_set_message('openid_canonical', $response->endpoint->canonicalID);
            }

            $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
            $sreg = $sreg_resp->contents();

            foreach ($sreg as $key => $value)
            {
                $data['success'] .= $this->_set_message('openid_content', array($key, $value), array('%s','%t'));
            }

            $pape_resp = Auth_OpenID_PAPE_Response::fromSuccessResponse($response);

            if ($pape_resp)
            {
                if ($pape_resp->auth_policies)
                {
                    $data['success'] .= $this->lang->line('openid_pape_policies_affected');

                    foreach ($pape_resp->auth_policies as $uri)
                    {
                        $data['success'] .= "<li><tt>$uri</tt></li>";
                    }

                    $data['success'] .= "</ul>";
                }
                else
                {
                    $data['success'] .= $this->lang->line('openid_pape_not_affected');
                }

                if ($pape_resp->auth_age)
                {
                    $data['success'] .= $this->_set_message('openid_auth_age', $pape_resp->auth_age);
                }

                if ($pape_resp->nist_auth_level)
                {
                    $data['success'] .= $this->_set_message('openid_nist_level', $pape_resp->nist_auth_level);
                }
            }
            else
            {
                $data['success'] .= $this->lang->line('openid_pape_noresponse');
            }
            break;
     }
    
      $data['pape_policy_uris'] = array(
        PAPE_AUTH_MULTI_FACTOR_PHYSICAL,
        PAPE_AUTH_MULTI_FACTOR,
        PAPE_AUTH_PHISHING_RESISTANT
    );
        
    $this->load->view('view_openid', $data);   
    }

}
?&gt;

views/view_openid.php

&lt;html&gt;
  &lt;head&gt;&lt;title&gt;PHP OpenID Authentication Example&lt;/title&gt;&lt;/head&gt;
  &lt;style type="text/css"&gt;
      * {
        font-family: verdana,sans-serif;
      }
      body {
        width: 50em;
        margin: 1em;
      }
      div {
        padding: .5em;
      }
      table {
        margin: none;
        padding: none;
      }
      .alert {
        border: 1px solid #e7dc2b;
        background: #fff888;
      }
      .success {
        border: 1px solid #669966;
        background: #88ff88;
      }
      .error {
        border: 1px solid #ff0000;
        background: #ffaaaa;
      }
      #verify-form {
        border: 1px solid #777777;
        background: #dddddd;
        margin-top: 1em;
        padding-bottom: 0em;
      }
  &lt;/style&gt;
  &lt;body&gt;
    <h1>PHP OpenID Authentication Example</h1>
    <p>
      This example consumer uses the <a
      href="http://www.openidenabled.com/openid/libraries/php/">PHP
      OpenID</a> library. It just verifies that the URL that you enter
      is your identity URL.
    </p>

    &lt;?php if (isset($msg)) { echo "<div class=\"alert\">$msg</div>"; } ?&gt;
    &lt;?php if (isset($error)) { echo "<div class=\"error\">$error</div>"; } ?&gt;
    &lt;?php if (isset($success)) { echo "<div class=\"success\">$success</div>"; } ?&gt;

    <div id="verify-form">
      &lt;form method="post" action="&lt;?php echo site_url('test/index'); ?&gt;"&gt;
        Identity&nbsp;URL:
        &lt;input type="hidden" name="action" value="verify" /&gt;
        &lt;input type="text" name="openid_identifier" value="" /&gt;

        <p>Optionally, request these PAPE policies:</p>
        <p>
        &lt;?php foreach($pape_policy_uris as $i => $uri): ?&gt;
          &lt;input type="checkbox" name="policies[]" value="&lt;?php echo $uri; ?&gt;" /&gt;
          &lt;?php echo $uri; ?&gt;<br />
        &lt;?php endforeach; ?&gt;
        </p>

        &lt;input type="submit" value="Verify" /&gt;
      &lt;/form&gt;
    </div>
  &lt;/body&gt;
&lt;/html&gt;

views/view_policy.php

&lt;html&gt;
  &lt;head&gt;&lt;title&gt;PHP OpenID Policy Example&lt;/title&gt;&lt;/head&gt;
  &lt;body&gt;
    <h1>PHP OpenID Policy Example</h1>
    <p>
      This page could display your policy.
    </p>
  &lt;/body&gt;
&lt;/html&gt;
Clone this wiki locally