为PHPBB加一个oauth认证方式统一登陆SSO
tag:phpbb,sso,统一登陆,oauth2,oauth
以下文章只是讲述我做这个东西的一个原理,主要实现是采用主站的认证来实现本站点的登陆,论坛采用隐式的密码认证方式;如果想要了解更多,[email protected];[email protected]?起分享!
操作步骤
一、将auth_oauth2.php加入论坛的includes/auth/这个目录当中,这是一个OAUTH的插件,使其支持这种认证方式
二、将caijicheOauthClient.php这个文件加入PHPBB的根目录中,这个文件是CAIJICHE的oauth客户端文件;
三、将论坛的数据库bbs_config表中的auth_method的值改成“oauth2”,说明使用oauth2认证;
四、为了使后台管理员也可以使用这种认证方式,把functions.php中的以下这段注释掉
if ($admin && utf8_clean_string($username) != utf8_clean_string($user->data['username']))
{
// We log the attempt to use a different username...
add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
trigger_error('NO_AUTH_ADMIN_USER_DIFFER');
}
否则会报不匹配的错误;
五、更改注册链接:
将functions.php中的函数page_header中的数组中“U_REGISTER”的值改成“http://www.caijiche.com/reg”
六、更改忘记密码链接:将functions.php中的函数page_header中的数组中“ U_SEND_PASSWORD ”的值改成“http://www.caijiche.com/getpwd”
phpbb报一些警告错误的解决办法:
将对应的函数改成静态函数
七、语言文件:"登录" 改成 "使用采集车帐号登陆" "用户名(USERNAME)"改成 "用户名[email]"
以下是auth_oauth2.php的内容
这个文件主要还是参考auth_db.php简单改动了一下
<?php
/**
* Database auth plug-in for phpBB3
*
* Authentication plug-ins is largely down to Sergey Kanareykin, our thanks to him.
*
* This is for authentication via the integrated user table
*
* @package login
* @version $Id: auth_db.php 10431 2010-01-20 00:20:46Z bantu $
* @copyright (c) 2005 phpBB Group
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
exit;
}
/**
* Login function
*/
function login_oauth2(&$username, &$password)
{
global $db, $config,$phpbb_root_path;
include ($phpbb_root_path . 'caijicheOauthClient.php');//将客户端的类含进来
require_once($phpbb_root_path.'common.php');
require_once($phpbb_root_path.'includes/functions_user.php');
// require_once($phpbb_root_path.'includes/functions_module.php');
// 密码为空
if (!$password)
{
return array(
'status' => LOGIN_ERROR_PASSWORD,
'error_msg' => 'NO_PASSWORD_SUPPLIED',
'user_row' => array('user_id' => ANONYMOUS),
);
}
//用户名为空
if (!$username)
{
return array(
'status' => LOGIN_ERROR_USERNAME,
'error_msg' => 'LOGIN_ERROR_USERNAME',
'user_row' => array('user_id' => ANONYMOUS),
);
}
$client_config = array(
'client_id' => "3c2d81228736786e5e846fewqrewqrfedsfadsafre",
'client_secret' => "f6996b15ewqrewqt434f4342e237abf4"
);
$client = new CaijicheOAuthClient($client_config);
//$par['username'] = "[email protected]";
//$par['password'] = '$caijiche$';
$par['username'] = $username;
$par['password'] = $password;
$o_url = $client->getAccessToken($par,'password');
//var_dump($o_url);
if(isset($o_url['access_token'])){
$caijiche_user = $client->getUserInfo($o_url['access_token']);
// var_dump($caijiche_user);
}
$password='$www.CAIJICHE.com';//在这里更换用户的用户名和密码
$username=$caijiche_user['user_nick'];
$useremail=$caijiche_user['user_email'];//用户邮箱
$sql = 'SELECT user_id, username, user_password, user_passchg, user_pass_convert, user_email, user_type, user_login_attempts
FROM ' . USERS_TABLE . "
WHERE username_clean = '" . $db->sql_escape(utf8_clean_string($username)) . "'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if (!$row)
{
$timezone = date('Z') / 3600;
$is_dst = date('I');
if ($config['board_timezone'] == $timezone || $config['board_timezone'] == ($timezone - 1))
{
$timezone = ($is_dst) ? $timezone - 1 : $timezone;
if (!isset($user->lang['tz_zones'][(string) $timezone]))
{
$timezone = $config['board_timezone'];
}
}
else
{
$is_dst = $config['board_dst'];
$timezone = $config['board_timezone'];
}
//用户所属组
$coppa=false;
$group_name = ($coppa) ? 'REGISTERED_COPPA' : 'REGISTERED';
$sql = 'SELECT group_id
FROM ' . GROUPS_TABLE . "
WHERE group_name = '" . $db->sql_escape($group_name) . "'
AND group_type = " . GROUP_SPECIAL;
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
$group_id = $row['group_id'];
if (($coppa ||
$config['require_activation'] == USER_ACTIVATION_SELF ||
$config['require_activation'] == USER_ACTIVATION_ADMIN) && $config['email_enable'])
{
$user_actkey = gen_rand_string(10);
$key_len = 54 - (strlen($server_url));
$key_len = ($key_len < 6) ? 6 : $key_len;
$user_actkey = substr($user_actkey, 0, $key_len);
$user_type = USER_INACTIVE;
$user_inactive_reason = INACTIVE_REGISTER;
$user_inactive_time = time();
}
else
{
$user_type = USER_NORMAL;
$user_actkey = '';
$user_inactive_reason = 0;
$user_inactive_time = 0;
}
//如果这个用户不存在,则自动注册之,然后再登录
$user_row = array(
'username' => utf8_normalize_nfc($username),
'user_password' => phpbb_hash($password),
'user_email' => strtolower($useremail),
'group_id' => (int) $group_id,
'user_timezone' => 0,
'user_dst' => $is_dst,
'user_lang' => 'zh_cmn_hans',
'user_type' => $user_type,
'user_actkey' => $user_actkey,
'user_ip' => $user->ip,
'user_regdate' => time(),
'user_inactive_reason' => $user_inactive_reason,
'user_inactive_time' => $user_inactive_time,
'user_dateformat' => 'Y-m-d G:i',
);
$user_id = user_add($user_row);
if($user_id){
$sql = 'SELECT user_id, username, user_password, user_passchg, user_pass_convert, user_email, user_type, user_login_attempts
FROM ' . USERS_TABLE . "
WHERE username_clean = '" . $db->sql_escape(utf8_clean_string($username)) . "'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
}else{
return array(
'status' => LOGIN_ERROR_USERNAME,
'error_msg' => 'LOGIN_ERROR_USERNAME',
'user_row' => array('user_id' => ANONYMOUS),
);
}
}
$show_captcha = $config['max_login_attempts'] && $row['user_login_attempts'] >= $config['max_login_attempts'];
//这一段,好像是密码登录错误次数的统一
// If there are too much login attempts, we need to check for an confirm image
// Every auth module is able to define what to do by itself...
if ($show_captcha)
{
// Visual Confirmation handling
if (!class_exists('phpbb_captcha_factory'))
{
global $phpbb_root_path, $phpEx;
include ($phpbb_root_path . 'includes/captcha/captcha_factory.' . $phpEx);
}
$captcha =& phpbb_captcha_factory::get_instance($config['captcha_plugin']);
$captcha->init(CONFIRM_LOGIN);
$vc_response = $captcha->validate($row);
if ($vc_response)
{
return array(
'status' => LOGIN_ERROR_ATTEMPTS,
'error_msg' => 'LOGIN_ERROR_ATTEMPTS',
'user_row' => $row,
);
}
else
{
$captcha->reset();
}
}
//接下来采用oauth2的password模式登录
//这一段好像是新旧密码转换功能
// If the password convert flag is set we need to convert it
if ($row['user_pass_convert'])
{
// in phpBB2 passwords were used exactly as they were sent, with addslashes applied
$password_old_format = isset($_REQUEST['password']) ? (string) $_REQUEST['password'] : '';
$password_old_format = (!STRIP) ? addslashes($password_old_format) : $password_old_format;
$password_new_format = '';
set_var($password_new_format, stripslashes($password_old_format), 'string');
if ($password == $password_new_format)
{
if (!function_exists('utf8_to_cp1252'))
{
global $phpbb_root_path, $phpEx;
include($phpbb_root_path . 'includes/utf/data/recode_basic.' . $phpEx);
}
// cp1252 is phpBB2's default encoding, characters outside ASCII range might work when converted into that encoding
// plain md5 support left in for conversions from other systems.
if ((strlen($row['user_password']) == 34 && (phpbb_check_hash(md5($password_old_format), $row['user_password']) || phpbb_check_hash(md5(utf8_to_cp1252($password_old_format)), $row['user_password'])))
|| (strlen($row['user_password']) == 32 && (md5($password_old_format) == $row['user_password'] || md5(utf8_to_cp1252($password_old_format)) == $row['user_password'])))
{
$hash = phpbb_hash($password_new_format);
// Update the password in the users table to the new format and remove user_pass_convert flag
$sql = 'UPDATE ' . USERS_TABLE . '
SET user_password = \'' . $db->sql_escape($hash) . '\',
user_pass_convert = 0
WHERE user_id = ' . $row['user_id'];
$db->sql_query($sql);
$row['user_pass_convert'] = 0;
$row['user_password'] = $hash;
}
else
{
// Although we weren't able to convert this password we have to
// increase login attempt count to make sure this cannot be exploited
$sql = 'UPDATE ' . USERS_TABLE . '
SET user_login_attempts = user_login_attempts + 1
WHERE user_id = ' . $row['user_id'];
$db->sql_query($sql);
return array(
'status' => LOGIN_ERROR_PASSWORD_CONVERT,
'error_msg' => 'LOGIN_ERROR_PASSWORD_CONVERT',
'user_row' => $row,
);
}
}
}
//检查用户输入的密码是否正确
// Check password ...
if (!$row['user_pass_convert'] && phpbb_check_hash($password, $row['user_password']))
{
// Check for old password hash...
if (strlen($row['user_password']) == 32)
{
$hash = phpbb_hash($password);
// Update the password in the users table to the new format
$sql = 'UPDATE ' . USERS_TABLE . "
SET user_password = '" . $db->sql_escape($hash) . "',
user_pass_convert = 0
WHERE user_id = {$row['user_id']}";
$db->sql_query($sql);
$row['user_password'] = $hash;
}
//当登录成功时,将用户重试的次数清零
if ($row['user_login_attempts'] != 0)
{
// Successful, reset login attempts (the user passed all stages)
$sql = 'UPDATE ' . USERS_TABLE . '
SET user_login_attempts = 0
WHERE user_id = ' . $row['user_id'];
$db->sql_query($sql);
}
// 用户未激活时返回的错误消息
if ($row['user_type'] == USER_INACTIVE || $row['user_type'] == USER_IGNORE)
{
return array(
'status' => LOGIN_ERROR_ACTIVE,
'error_msg' => 'ACTIVE_ERROR',
'user_row' => $row,
);
}
//用户登录成功
// uccessful login... set user_login_attempts to zero...
return array(
'status' => LOGIN_SUCCESS,
'error_msg' => false,
'user_row' => $row,
);
}
// Password incorrect - increase login attempts
$sql = 'UPDATE ' . USERS_TABLE . '
SET user_login_attempts = user_login_attempts + 1
WHERE user_id = ' . $row['user_id'];
$db->sql_query($sql);
// Give status about wrong password...
return array(
'status' => ($show_captcha) ? LOGIN_ERROR_ATTEMPTS : LOGIN_ERROR_PASSWORD,
'error_msg' => ($show_captcha) ? 'LOGIN_ERROR_ATTEMPTS' : 'LOGIN_ERROR_PASSWORD',
'user_row' => $row,
);
}
caijicheOauthClient.php的主要内容符下:
<?php
class CaijicheOAuthClient{
//private $params = array();//参数数组
//客户端的用户名
public $client_id;
//客户端的密码
public $client_secret;
//返回网址
public $callback_url;
private $requestToken;
private $requestTokenSecret;
private $access_token;
private $expires_in = 3600;//access_token的生命周期。
// 服务器描述信息
private $server = array(
"server_uri" => "http://www.caijiche.com",
'request_token_uri' => 'http://www.caijiche.com/?mod=OAuth&action=requestToken',
'authorize_uri' => 'http://www.caijiche.com/?mod=OAuth&action=authorize',
'access_token_uri' => 'http://www.caijiche.com/?mod=OAuth&action=accesstoken',//获取请求令牌
'getuserinfo_uri' => 'http://www.caijiche.com/?mod=OAuth&action=getUserInfo',//获取用户信息的服务器地址
);
/**
* authorize接口
*
* @param string $url 授权后的回调地址,站外应用需与回调地址一致,站内应用需要填写canvas page的地址
* @param string $response_type 支持的值包括 code 和token 默认值为code
* @param string $state 用于保持请求和回调的状态。在回调时,会在Query Parameter中回传该参数
* @return array
*/
public function getAuthorizeURL( $url=NULL, $response_type = 'code', $state = NULL, $display = NULL ) {
$params = array();
$params['client_id'] = $this->client_id;
$params['redirect_uri'] = is_null($url)?$this->callbackurl:$url;
$params['response_type'] = $response_type;
$params['state'] = $state;
//log::debug("getAuthorizeURL params".var_export($params,true));
return $this->server['authorize_uri']. "&" . http_build_query($params);
}
/**
* 构造函数
* @param array $config
*/
public function __construct($config)
{
if(is_array($config)){
if(isset($config['client_id']))$this->client_id = $config['client_id'];
if(isset($config['client_secret']))$this->client_secret = $config['client_secret'];
if(isset($config['callback_url']))$this->callbackurl = $config['callback_url'];
}
}
/**
* 获取未授权的令牌
*/
public function getRequestToken(){
$data = "oauth_client_key=".$this->key;
$result = json_decode($this->do_call($this->server['request_token_uri'],$data));
$this->requestToken = $result->token;
$this->requestTokenSecret = $result->token_secret;
return $this->requestToken;
}
/**
* 发送请求用的
* @param unknown_type $url
* @param unknown_type $postdata
*/
private function do_call($url, $postdata=NULL)
{
//log::debug("do_call url = " . $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_URL, $url);
$ret =curl_exec($ch);
//var_dump($ret);
//log::debug("do_call return:" . var_export($ret,true));
curl_close($ch);
return $ret;
}
/**
* access_token接口
*
* @param string $type 请求的类型,可以为:code, password, token
* @param array $keys 其他参数:
* - 当$type为code时: array('code'=>..., 'redirect_uri'=>...)
* - 当$type为password时: array('username'=>..., 'password'=>...)
* - 当$type为token时: array('refresh_token'=>...)
* @return array
*/
public function getAccessToken( $keys ,$type = 'code' ) {
$params = array();
$params['client_id'] = $this->client_id;
$params['client_secret'] = $this->client_secret;
if($type=='code'){
$params['grant_type'] = 'authorization_code';
$params['code'] = $keys['code'];
$params['redirect_uri'] = $keys['redirect_uri'];
}else if($type=='password'){
$params['grant_type'] = 'password';
$params['username'] = $keys['username'];
$params['password'] = $keys['password'];
}else{
//未知的请求类型
return;
}
$response = $this->do_call($this->server['access_token_uri']."&".http_build_query($params));
$token = json_decode($response, true);//转换成数组
if ( is_array($token) && !isset($token['error']) ) {
$this->access_token = $token['access_token'];
$this->expires_in = $token['expires_in'];
} else {
//throw new OAuthException("get access token failed." . $token['error']);
//授权出错
}
return $token;
}
/**
*
* 获取用户访问信息
* @param unknown_type $access
* @param unknown_type $openid
* @param unknown_type $aid
*/
public function getUserInfo($access_token){
$data="access_token={$access_token}&format=json";
$user=$this->do_call($this->server['getuserinfo_uri'],$data);
$arr=json_decode($user,true);
return $arr;
}
/**
* 签名生成算法
* @param array $params API调用的请求参数集合的关联数组,不包含sign参数
* @param string $secret 签名的密钥即获取access token时返回的session secret
* @return string 返回参数签名值
*/
function getSignature($params, $secret)
{
$str = ''; //待签名字符串
//先将参数以其参数名的字典序升序进行排序
ksort($params);
//遍历排序后的参数数组中的每一个key/value对
foreach ($params as $k => $v) {
//为key/value对生成一个key=value格式的字符串,并拼接到待签名字符串后面
$str .= "$k=$v";
}
//将签名密钥拼接到签名字符串最后面
$str .= $secret;
//通过md5算法为签名字符串生成一个md5签名,该签名就是我们要追加的sign参数值
return md5($str);
}
}
?>