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?
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"
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With