我成功使用Facebook SDK(PHP)将用户连接到我的网站,但我们在验证帐户时遇到问题。他们的帐户已成功通过身份验证,但出于某种原因,我的网站会话已被清除。
流速:
我正在使用Facebook SDK(PHP),我的网站使用CakePHP框架
非常感谢任何帮助。
答案 0 :(得分:2)
我无法告诉你什么是删除你的会话,但你可能想尝试这个(适合我)
使用Javascript SDK显示将打开弹出窗口以连接到FB的登录按钮
将js SDK添加到您的页面中,如下所示:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '<?php echo FB_API_ID; ?>', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.login', function() {
new Request({
'method': 'get',
'url': '<?php echo $this->Html->url(array('controller'=>'users','action'=>'login_fb'));?>',
'onSuccess': function(result){
window.location.reload();
}
}).send();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
在auth.login
事件中,我正在使用ajax调用/ users / login_fb,它将使用Facebook SDK检查facebook会话:
App::import('Lib', 'facebook_sdk/facebook');
// "MyAuth" is a custom Auth Component that extends the normal Auth component
$this->MyAuth->facebook = new Facebook(array(
'appId' => FB_API_ID,
'secret' => FB_SECRET,
'cookie' => true,
));
$me = null;
$session = $this->MyAuth->facebook->getSession();
if ($session) {
try {
$uid = $this->MyAuth->facebook->getUser();
$me = $this->MyAuth->facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
if ($me) {
$this->Session->write('FbLogin.session',$session);
$this->Session->write('FbLogin.user',$me);
$UserModel = ClassRegistry::init('User');
$user = $UserModel->findByUid($me['id']);
if(!$user){
$UserModel->create();
$user_data = array( 'username'=>$me['username'],
'name'=>$me['first_name'],
'lastname'=>$me['last_name'],
'email'=>$me['email'],
'group_id'=>GROUP_VISITOR,
'uid'=>$me['id']
);
$UserModel->save($user_data);
$user['User']['id'] = $UserModel->id;
}
$this->Session->write($this->MyAuth->sessionKey, $user['User']);
$this->MyAuth->_loggedIn = true;
}
}
主要的想法是..在js我调用ajax来检查fb会话然后将其保存在蛋糕会话中,并且js将刷新页面
答案 1 :(得分:1)
可能值得检查Cake安全级别,它可能正在进行引用检查(我认为它在“高”设置中执行此操作,也可能是“中等”),这会使会话无效。
答案 2 :(得分:1)
我无法找出会话重置的原因,因此决定不使用SDK进行身份验证。这就是我用来代替的。
$code = (isset ($_REQUEST['code']) ? $_REQUEST['code'] : null);
if (empty ($code)) {
$dialogUrl = 'http://www.facebook.com/dialog/oauth?client_id=' . $this->appId . '&redirect_uri=' . urlencode($this->url) . '&scope=' . implode(',', $this->scope);
header('Location: ' . $dialogUrl);
die;
}
else {
$tokenUrl = 'https://graph.facebook.com/oauth/access_token?client_id=' . $this->appId . '&redirect_uri=' . urlencode($this->url) . '&client_secret=' . $this->secret . '&code=' . $code;
$accessToken = file_get_contents($tokenUrl);
$this->Session->write('facebookAccessToken', $accessToken);
$graphUrl = 'https://graph.facebook.com/me?' . $accessToken;
$fbUser = json_decode(file_get_contents($graphUrl));
if ($fbUser) {
...
}
}