Facebook session in an iframe application breaks ajax calls
I've a facebook application, which conncets to facebook via the PHP-SDK.
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET_KEY,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
Everything is fine, I let the browser open and don't respond to my app. After a while I try to send a form in the app via ajax. It seems that the session is invalid? Facebook will authorize my app again load the ajax url into the browsers address bar and attach the new session param to that url and breaks the app.
Is there anything I could do to pretend facebook to "reload" or pass the ajax/form action to the browser address bar? Before every request is processed I check whether the user is still active or not, that might be the problem?
$user = $facebook->getUser();
if ($user != 0) {
if($this->userProfile == null){
try {
// Proceed knowing you have a logged in user who's authenticated.
开发者_StackOverflow社区 $this->userProfile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
}else{
$this->userProfile = null;
}
if ($this->userProfile != null) {
$filterChain->run();
} else {
$loginUrl = $facebook->getLoginUrl(
array('scope' => 'publish_stream','redirect_uri' => 'REDIRECT_URI'));
}
echo("<script> top.location.href='" . $loginUrl . "'</script>");
Should I use an other approch? Thanks in advance!
You really shouldn't be processing ajax calls the same way as regular page fetches. Generally if something like an expired session happens within an ajax process you want to send an error code back to the main page and let it handle it at the top level.
I'm guessing that the info you send back from this ajax request gets immediately parsed as HTML? Which means that if you send back a <script>top.location=xxx</script>
block, it gets executed and redirects the browser to the new location. Again that's probably not the best way to handle things, but it would still work if the redirect_uri were set appropriately (to the url of the page as a whole). Because the getLoginUrl() is called while within the ajax page, the redirect_uri is set to that url instead, so after the new authorization is completed that's where the browser is sent back to (at the top level now). So while probably not the best overall structure, a quick workaround would be to override the redirect_uri setting when you are within an ajax call, and make it point to the parent page instead of itself.
精彩评论