How Does Facebook SDK Login Work? - javascript

If there is a github repo with the unminified source that would also work as an answer.
https://connect.facebook.net/en_US/sdk.js
I'm new to oAuth in general but my assumption was that there was no way to get the auth token from an opened window. But in there example they show something like this-
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
When testing in Plunkr, this opened a new window, I logged in, no redirect occurred, but I was able to use the auth token. I wanted to investigate how they did this but wasn't able to find the source.
Does anyone know how they passed the token from the opened window back to the original window?

Related

Refreshing FB Access Token with Javascript SDK

For context I am trying to build a small microsite to pull social media insights from Facebook. I am looking to build a Django backend and React front end.
I would like to implement FB login with the Javascript SDK since according to the docs this refreshes the access token each time a FB call is made using the SDK.
I have a very simple login script taken from FB official docs which literally just logs in the user and then outputs the list of accounts the user has access to.
The issue is that, despite refreshing the page (and therefore performing an API request) the data expiration date doesn’t extend (it still displays the date of first login).
Is anyone familiar with the Javascript SDK and whether this is normal behaviour?
function statusChangeCallback(response) { // Called with the results from FB.getLoginStatus().
console.log(response);
if (response.status === 'connected') { // Logged into your webpage and Facebook.
testAPI();
FB.getAuthResponse(function(response){
console.log(response.authResponse.accessToken);
});
} else { // Not logged into your webpage or we are unable to tell.
document.getElementById('status').innerHTML = 'Please log ' +
'into this webpage.';
}
}
function checkLoginState() { // Called when a person is finished with the Login Button.
FB.getLoginStatus(function(response) { // See the onlogin handler
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'APP_ID_GOES_HERE',
cookie : true, // Enable cookies to allow the server to access the session.
xfbml : true, // Parse social plugins on this webpage.
version : 'v13.0' // Use this Graph API version for this call.
});
FB.getLoginStatus(function(response) { // Called after the JS SDK has been initialized.
statusChangeCallback(response); // Returns the login status.
});
};
function testAPI() { // Testing Graph API after login. See statusChangeCallback() for when this call is made.
console.log('Welcome! Fetching your information.... ');
FB.api('/me/accounts',
function(response) {
console.log(response)
});
}
function logout_js_user(){
FB.logout(function(response) {
// Person is now logged out
});
};
FB.getLoginStatus does refresh the Token, but not on every Page call. It only refreshes the Token when it is not valid anymore. That is why the expiration data does not change.
You can can a more accurate status with the second parameter of the function set to true, but be aware that this might affect performance:
FB.getLoginStatus(function(response) {
// this will be called when the roundtrip to Facebook has completed
}, true);
If you call FB.getLoginStatus on every page load, be careful not to
set this parameter for each as it will significantly increase the
number of requests to Facebook's servers, and thus decrease the
performance of your application.
Side note: ou can use FB.login to make the login less complicated (in my opinion) - here's an old but still valid article about that: https://www.devils-heaven.com/facebook-javascript-sdk-login/

FB.getLoginStatus return authResponse null even after user login through Facebook login dialog

FB.getLoginStatus return authResponse as null, im unable to determine if i need to open the login dialog again. when user is prompt with login dialog again the previous permission is being reseted. For example, when user agree to allow app to manage a particular page. When login dialog is prompt again, they are unable to see the page that is previous approve for manage_pages permission. Re-login revoke the permission to manage that particular pages.
What can i do to prevent Facebook to prompt login dialog again? I am using v3.3 for facebook login:
checkLoginState(){
var self = this;
window.FB.getLoginStatus(function(response) {
console.log( 'login status' + JSON.stringify(response));
if(response.authResponse === null){
self.showLogin();
}
}, true);
}
showLogin(){
var self = this;
// //fb permission scope and login function
window.FB.login(function(response){
console.log('has access token', response.authResponse)
if (response.authResponse) {
console.log('has access token' + response.authResponse.accessToken);
self.setState({
fb_access_token: response.authResponse.accessToken
})
console.log('self.state', self.state)
self.storeFBToken();
self.retrieveFbProfile();
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'public_profile, manage_pages, email, pages_messaging, pages_show_list'});
}
I just tried with a production facebook app id and test it on a https page. getLoginStatus is returning access token correctly. it is still unknown to me why getLoginStatus does not work with a development facebook app id on localhost.

Facebook Users logging fine but not showing up in api requests

I have an Android and Web app that uses the Parse backend with FB login. I just created the Web version and I'm having an issue with my users that log in through web. They are being saved to the backend just fine along with their FB info, but for some reason, when I make a me/friends api request, I cannot find any of my friends that have logged in through my website (anyone that logged in through the Android app shows up just fine). This leads me to believe that even though the Parse login worked fine, there is probably an issue with FB login. My code is exactly as the parse docs describe:
Parse.FacebookUtils.logIn(null, {
success: function(user) {
if (!user.existed()) {
FB.api('/me', function(response) {
var currentUser = Parse.User.current();
if (currentUser) {
currentUser.set("fbName", response.name);
currentUser.set("facebookId", response.id);
currentUser.save();
window.location = "index.html";
} else {
alert("Login Did Not Work!");
}
});
} else {
FB.api('/me', function(response) {
Parse.User.current().set("fbName", response.name);
Parse.User.current().set("facebookId", response.id);
Parse.User.current().save();
window.location = "index.html";
});
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
Is there something else I should be doing here?
If anyone is having the same problem, I simply forgot to include the user_friends permission (or any permission for that matter, but user_friends is what I wanted).

What oauthRedirectURL in openFB should look like, using a cordova app?

I came across this openFB plugin to make facebook requests without the sdk, that can be used in cordova,
I got it to log in the user in facebook, the thing is as oauthRedirectURL I end up in a white page, that says Success and I'm not sure how to get the user back to the app,
if (runningInCordova) {
oauthRedirectURL = "https://www.facebook.com/connect/login_success.html";
}
Question is,
What url can i use to point my app ?
User ends up in this screen after the login
-edit-
I found solutions like http://localhost.com/oauthcallback.html but I don't have a apache2 in the cordova environament..
-2nd edit-
This is my current code,
openFB.init({appId: 'xxxxxxxxyyyyyyyy'});
openFB.login( function(response) {
if(response.status === 'connected') {
alert('Facebook login succeeded, got access token: ' + response.authResponse.token);
} else {
alert('Facebook login failed: ' + response.error);
}
}, {scope: 'email'});
This the line of the lib that fills this value
if (runningInCordova) {
oauthRedirectURL = "https://www.facebook.com/connect/login_success.html";
}
I haven't used openFB before but I'm pretty sure it's based on the following docs:
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.3
If you go to the section "logging people in" you'll see the following message:
redirect_uri. The URL that you want to redirect the person logging in
back to. This URL will capture the response from the Login Dialog. If
you are using this in a webview within a desktop app, this must be set
to https://www.facebook.com/connect/login_success.html.
When a FB user grants permissions to your App, it will be redirected to the url https://www.facebook.com/connect/login_success.html?access_token=new_token&...
What you have to do now is monitor this url and get the access token provided, which you should store with the fb user id in order to perform any API call.
Googling how to do this with openFB I found a thread at the openFB github repo that should help: https://github.com/ccoenraets/OpenFB/issues/20#issuecomment-49249483 (is not totally related but it provides some code you can use)
This should be the code that will allow you to monitor the URL (extracted from the code provided on the thread):
if (runningInCordova) {
loginWindow.addEventListener('loadstart', function (event) {
var url = event.url;
if (url.indexOf("access_token=") > 0) {
// Get the token
}
});
}
Once you have obtained the access token and stored in your database, you should redirect to any other place of your App.
I hope it helps.
Javier.

Facebook login silently failing

I'm trying to implement login to a website with Facebook, using their JavaScript SDK. I understand that this is OAuth 2 under the hood, although that shouldn't even matter... I am setting things up using the async loader, and the FB variable exists and I can call functions in it. When I call FB.login(), another tab opens, flashes for a fraction of a second, and then closes. I then wind up back on my page, with no events having been triggered and no sign that anything has happened.
I have initialized the API as follows:
FB.init({
appId : facebookAppID,
channelUrl : channelFilePath,
status : true,
xfbml : true
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
console.log("Connected.");
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else if (response.status === 'not_authorized') {
console.log("Not logged in.");
} else {
console.log("Still not logged in.");
}
});
Then my login call is simply:
function loginFacebook() {
console.log("Trying to log in.");
FB.login();
}
One detail which might be relevant is that I'm running for development purposes on a nonstandard port, 1980 instead of 80. It's not easy for me to try port 80, because of where I'm running, but if it turns out to be the problem I absolutely can.
Thanks in advance. :)
It turned out to be the port. Yes - they check, apparently! The completely silent failure was really perplexing...

Categories

Resources