Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Facebook Access (from server) in JavasScript SDK

If I am using the server side flow to authenticate a user and acquire an access token, how can I set that access token in the JavaScript SDK and use it to make calls from the client side?

like image 296
Chris Lukic Avatar asked Oct 08 '22 15:10

Chris Lukic


1 Answers

Once the user has finished the server side authentication flow the user is already authorized for your app, all you need to do is to use the FB.getLoginStatus method:

FB.getLoginStatus(function(response) {
    if (response.status === "connected") {
        console.log("authResponse: ", response.authResponse);
        FB.api("me", function(response2) {
            console.log("Hey there " + response2.name);
        });
    }
    else if (response.status === "not_authorized") {
        // user is logged in to facebook but hasn't authorized your app, should not happen if he went through the server side authentication
    }
    else {
        // user is logged out of facebook, also should not happen
    }
}

As you can see you can simply use the js sdk to query the graph, there's no need to get the token manually, but in case you still need it, the authResponse should have the following format:

authResponse: {
    accessToken: "aaaaaaa",
    expiresIn: "bbbbbb",
    signedRequest: "cccccc",
    userID: "dddddd"
}

Edit

If the user is logged into facebook and has allowed and interacted with your app then yes the getLoginStatus should return a valid access token.
There are a few cases in which this is not the case, one of them being that the token has expired.

As it states in the Handling Invalid and Expired Access Tokens:

Desktop Web and Mobile Web apps which implement authentication with the Javascript SDK

Calling FB.getLoginStatus() or ensuring status: true is set when you call FB.init() means that the next time a user lands on your application and is signed into Facebook, the authResponse object you are passed as a result of those calls will contain a fresh, valid access token.

In this case, its simply the act of the user using your application which implicitly generates a new access token.

like image 186
Nitzan Tomer Avatar answered Oct 12 '22 12:10

Nitzan Tomer