Created
April 27, 2010 01:11
-
-
Save ydn/380177 to your computer and use it in GitHub Desktop.
simple code to require OpenID authentication on a page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php // simple code to require OpenID authentication on a page | |
/* | |
Requirements: | |
* PHP 5 | |
* OpenID Enabled PHP library (http://openidenabled.com/php-openid/) | |
Usage: | |
1) Put this code in a file on your server | |
2) Edit the "$realm" variable to be your domain | |
3) Load the page in a browser | |
4) Log into Yahoo! after being redirected | |
*/ | |
//suppress warnings caused by php openid lib as we need to redirect | |
error_reporting(E_ERROR | E_PARSE); | |
//php openid lib requires session | |
session_start(); | |
//ammend include path so we can include files consistently | |
$includePath = get_include_path().PATH_SEPARATOR.'php-openid-2.1.3'; | |
set_include_path($includePath); | |
//include openid files | |
//get openid lib from http://openidenabled.com/php-openid/ | |
require_once "Auth/OpenID/Consumer.php"; | |
require_once "Auth/OpenID/FileStore.php"; | |
require_once "Auth/OpenID/AX.php"; | |
//init basic openid auth url generation | |
$openidFileStore = new Auth_OpenID_FileStore('/tmp/'); | |
$openidConsumer =& new Auth_OpenID_Consumer($openidFileStore); | |
//safely fetch input | |
$filters = array( | |
'openid_identity' => FILTER_SANITIZESTRING, | |
'openid_mode' => FILTER_SANITIZESTRING, | |
'username' => FILTER_SANITIZESTRING, | |
); | |
$input = filter_var_array( $_REQUEST, $filters ); | |
//settings | |
$realm = 'http://example.com'; | |
$openidProvider = 'http://yahoo.com/'; | |
//if the user's not logged in, and there is an openid assertion param in the url, verify response | |
if ( !$input['username'] && 'id_res' == $input['openid_mode'] ) { | |
$verification = $openidConsumer->complete( $realm.$_SERVER['REQUEST_URI'] ); | |
if ( 'success' == $verification->status ) { | |
setcookie('username', $input['openid_identity'] ); | |
$input['username'] = $input['openid_identity']; | |
} else { | |
var_dump( $verification ); | |
} | |
//if the user's not logged in, redirect to log in | |
} elseif ( !$input['username'] ) { | |
$openidAuthRequest = $openidConsumer->begin( $openidProvider ); | |
$openidLoginRedirectUrl = $openidAuthRequest->redirectURL( | |
$realm, | |
$realm.$_SERVER['REQUEST_URI'] | |
); | |
header( 'Location: '.$openidLoginRedirectUrl ); | |
} | |
?> | |
Welcome, <?= $input['username'] ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment