I'm using the Facebook JavaScript SDK to implement login for my site. I've already got it working on Safari and Firefox, but not in Chrome.
After the FB.login method is called, I'm able to retrieve the access token from Facebook, but it's not setting the access token and user ID in the cookies like it does in Firefox and Safari. Currently, I'm manually writing the access token and the user ID to the cookies so the login flow works but it still bugs the heck out of me that the access token is not written in Chrome alone.
Has anybody come across this before and know a fix at hand? Much appreciated.
Below are my code for the init and login logic:
window.fbAsyncInit = function() {
FB.init({
appId : "#{AppConfig.facebook['app_id']}", // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
$(function() {
$(".fb-login-button").click(function() {
FB.login(function(response) {
if (response.authResponse) {
console.log("Welcome! Fetching your information...");
$.cookie("user_id", response.authResponse.userID);
$.cookie("access_token", response.authResponse.accessToken);
window.location = "#{oauth_facebook_callback_url}";
} else {
console.log("User cancelled login or did not fully authorize.");
}
}, {scope: 'publish_stream,offline_access,email,user_events,create_event,user_location'});
});
});
If you're testing your application locally, note that Google Chrome does not support cookies for local files (including localhost
) unless you start it with the --enable-file-cookies
flag. Chrome does, however, support cookies if you use your local IP address—127.0.0.1
— for testing.
You can view a discussion on this behavior here: http://code.google.com/p/chromium/issues/detail?id=535
(Answer modified from Why does Chrome ignore local jQuery cookies?)
Note that the JS SDK already does store the viewer's latest ID and access_token in the fbsr_APPID cookie. That cookie will be updated with the latest data each time a user uses FB.ui
, FB.login
, FB.getLoginStatus
with force = true
, or FB.init
with status: true
.
I highly recommend using this method instead of storing your own cookies, since it is signed with your app's secret key just like the signed_request parameter. You should follow the directions there to decode it, verify the signature, and if it's valid, use that. This will prevent forgery (but still may not prevent short-term replay attacks).