简体   繁体   中英

Facebook: Redirect after login, user session is empty?

I am trying to authenticate (login) a user into facebook while requesting some permissions inside an iframe app.

I am using the JS SDK in conjunction with the PHP SDK. So, first I check if the user is logged in and everything is ok using PHP $facebook->getUser() , when that fails I redirect the user to a page where this JS is run:

FB.getLoginStatus(function(response) {
    if (response.status === "connected") {
        // Ok, go home
    } else {
        FB.login(function(response) {
            if (response.authResponse) {
                // Ok, go home
            } else {
                // Cancelled, go home
            }
        }, {scope: '<?php echo implode(',', $this->permissions); ?>'});
    }
});

This would then create a login dialog asking for permissions. As you can see there are cases for when the user has authenticated/authorized properly and for when the dialog was canceled. In any of those cases I need to do a single thing: redirect back to the root of my application.

So, the dialog pops, the user logs in and then he is redirected back home, where I use PHP to getUser() .

The problem here is that, the first time the user is logged in and redirected, getUser() is always empty, there is no user session. If I refresh the facebook page holding my app's iframe, then there is session and permissions are properly set, indicating that the dialog has done it's job.

Any ideas of why would the first redirect not work?

I found similar issues, but non gives me a specific, working solution.

If anyone else has the same issue, here's what I've learned:

  1. Facebook claims to supply the session cookie to PHP after it's set with JS, but this is NOT true, at least not at all times!
  2. The only solution to this (at least the only one I could think of) is to manually pass the access token whenever you login with JS to your backend (PHP). Store it in a session there, and whenever avaialable use it instead of the access token the Facebook API is trying to use. Just call $api->setAccessToken($yourNewToken);
  3. You can keep on testing to see when exactly will the token be available, but for me it is usually available right after the second api call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM