I am trying FB login for a site for first time. I am able to see the FB button and the popup window shows with what appears to be correct FB login with my app name, so i think that part is good. my issue is after clicking login I enter the user/pass, then window closes and nothing else happens. I know I am logged in because when i click the FB again it pops up and closes, so i guess it knows I am logged in to FB. but i cant see any of my calls to write to console, and I am not sure how to make it do something else after the loging... Maybe I am not understanding what happens after the login to FB is successful, am i missing something? . here is what I have tried so far.
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXX', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
}
function doLogin() {
FB.login(function(response) {
if (response.authResponse) {
console.log('Hello! Getting account information.... ');
FB.api('/me', function(response) {
console.log('Hello, ' + response.name + '.');
});
} else {
console.log('User not fully authorize.');
}
});
}
// 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 testFbLogin() {
console.info("Testing you are Logged in...");
}
In your FB app configuration there are settings for the domains and subdomains this app can use.
I guess you are trying to use the login from some development machine which name do not match the configured parameters for domains and subdomains for your FB app.
If you inspect the network communication (Crome developer tools are excellent and easy to use for this) you will see the error that FB returns and this will give you better idea what is going on.
If this is the case, then:
Open /etc/hosts (unix) or C:\WINDOWS\system32\drivers\etc\hosts.
If your configured domain is example.com, then add this line:
127.0.0.1 dev.example.com
When you are testing, open dev.example.com in your browser and it should work.
As alternative you can edit your app at FB and set the "Site URL" to
http://localhost/myapppath or only http://localhost
Related
I'm working on a feature on our website to display my company's Facebook page posts on our Intranet site. I found this code and am having trouble.
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<ourappid',
xfbml : true,
version : 'v2.8'
});
FB.AppEvents.logPageView();
FB.login(function (response) {
if (response.authResponse) {
//alert("You are logged in");
FB.api('/ourpageurl/feed', function(response) {
console.log("response",response);
})
} else {
alert("Login attempt failed!");
}
}, { scope: 'public_profile' });
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
I do not control our company's Facebook page. Our social media director provided me with the app id. When I run the code above on a browser where I have not logged into Facebook with my username, I get a pop up window asking for my Facebook credentials. When I run this on a browser where I have an active Facebook session, the code does nothing. Nothing inside the login callback function is executed.
I've also tried skipping the FB.login portion and just running
FB.api('/ourpageurl/feed', function(response) {
console.log("response",response);
})
immediately after FB.AppEvents.logPageView();, but I get an error object back complaining about an access token. As far as I've been able to tell, in order to get an access token, I have to run the login method. What am I doing wrong here?
First of all: You can only call FB.login on user interaction, or browsers will block the popup. If done correctly, FB.login opens a popup where you can authorize the App with your user account.
I assume that is not what you want. For getting the feed of an unrestricted Page, you can use an App Access Token - it is the only Token that does not need user authorization. Access Tokens are meant to be kept secret, so you need to do that API call on your server, NOT on the client with JavaScript. You also need to think about caching the result, if a lot of users hit the Page where you read/show the feed, you may hit an API limit on Facebook.
About Tokens in general:
https://developers.facebook.com/docs/facebook-login/access-tokens/
http://www.devils-heaven.com/facebook-access-tokens/
How can I perform an automatic Facebook Login with the Facebook JavaScript SDK like Hootsuite do?
With my code I can just access my Facebook app with my Facebook Account, but how can I create a non-facebook login to my website, but also be logged in to Facebook over the app?
Here is my code for normal Facebook Login:
<div id="fb-root"></div>
<script>
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
document.getElementById('status').innerHTML = 'Verbunden';
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
window.fbAsyncInit = function() {
FB.init({
appId : 'AppID',
xfbml : true,
status : true,
cookie : true,
version : 'v2.1'
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/de_DE/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
An App Login (and that is what hootsuite is using) implies that you must login to Facebook first - So there is nothing else to do. If you use the Facebook Login on hootsuite, you will need to sign in to Facebook first.
Don´t worry too much about Access Tokens, the JavaScript SDK usually takes care about that unless you want to do more complicated things like generating Extended Access Tokens and whatnot.
Login is very easy with the JavaScript SDK: https://developers.facebook.com/docs/reference/javascript/FB.login/v2.2
Just make sure you call that function on user interaction (mouse click) - else it may get blocked in the browser.
Edit: I see that you want to auto-login with Facebook if someone logs in on your website WITHOUT Facebook login. Well, that is not possible. Access Tokens are used for API calls, not for login. If a user is not logged in on Facebook, you can´t just log him in automatically. But you CAN store Access Tokens for later usage, those are valid even when the User is not logged in. About how to use Access Tokens and which ones are available, take a look at those articles:
https://developers.facebook.com/docs/facebook-login/access-tokens/
http://www.devils-heaven.com/facebook-access-tokens/
http://www.devils-heaven.com/extended-page-access-tokens-curl/
is it correct that the Facebook API access token changes on every pageload?
I thought once a token was obtained, it would stay the same until expiry.
I am using the Facebook SDK for Javascript.
Facebook says that with this SDK, there is no need to manually manage access tokens. The SDK just does it.
But is it correct that the token changes on every pageload?
My code is this:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxx',
status : true,
xfbml : false,
cookie : true
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function check() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
console.log(response);
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
console.log(response);
} else {
// the user isn't logged in to Facebook.
console.log(response);
}
});
}
</script>
<span onClick="check()">test</span>
I just tested this and you are right, the Token changes with every page refresh. I would not worry much about it though, when using one of the SDKs (JavaScript, PHP, ...) you most likely don´t need to think about the Access Tokens at all.
And even if you need them (for managing Pages, for example), you can just use the last one.
The "older" Tokens are still valid btw, they don´t get invalidated. But they will stop working after 2 hours anyway.
There is also a second parameter you can set to "true": https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/ (see "Roundtrips to Facebook's servers") - which may have explained the new Token, but you´re not using that either.
Facebook has recently changed its process of refreshing access token.
Try to use this if it works in you case:
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
EDIT:
This will might help you as well. Link
I Used the instructions here: https://parse.com/docs/js_guide#fbusers (Facebook login using Javascript) to write a login page that uses Facebook authentication.
When I first login, all works perfect (Except a 'FB.init has already been called' warning in the console.)
When I Refresh the page, I see a "FB.login() Called when user is already connected" Error in the console. But I still get a "User logged in through Facebook" message as expected.
If I hit refresh Again, I now get a message box saying "User cancelled the facebook login or did not fully authorize" (Msgbox is defined in the code),
and in the console I now see that the POST to https://api.parse.com/1/users returned a 400 Error, as opposed to before in which i got a 200 OK.
This is my HTML Code:
<html><head></head><body> <div id="fb-root"></div>
<script src="http://www.parsecdn.com/js/parse-1.2.9.min.js"></script>
<script>Parse.initialize("<key>", "<key>"); // Additional JS functions here
window.fbAsyncInit = function() {
Parse.FacebookUtils.init({
appId : '<id>', // App ID
channelUrl : '<path>/Channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
Parse.FacebookUtils.logIn(null, {
success: function(user) {
if (!user.existed()) {
alert("User signed up and logged in through Facebook!");
} else {
alert("User logged in through Facebook!");
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
};
// Load the SDK asynchronously
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
</body> </html>
I would appreciate it if anyone could spot the problem.
Thanks!
"User cancelled the facebook login or did not fully authorize" means that you are already logged in. Use chrome's developer tools console to check if your current user using this commmand:
Parse.User.current()
If you get an object, you are already logged in.
You can use Parse.User.logOut() to logout, then Parse.User.current() should return a null!
Also you can use Parse.User.current().get('authData')['facebook'], as mentioned here
Notes:
If logging out from parse logs you out of facebook, update your parse reference
I'm using new Facebook login:
window.fbAsyncInit = function () {
FB.init({
appId: '#facebookAppId', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true, // parse XFBML
oauth: true
});
runFbInitCriticalCode();
};
function runFbInitCriticalCode() {
// Additional initialization code here
FB.Event.subscribe('auth.login', function () {
window.location = "/facebookPostAuth.aspx";
});
FB.Event.subscribe('auth.logout', function (response) {
});
// Hack to fix http://bugs.developers.facebook.net/show_bug.cgi?id=20168 for IE7/8/9
FB.UIServer.setLoadedNode = function (a, b) { FB.UIServer._loadedNodes[a.id] = b; };
};
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
} (document));
Anyone knows why after the popup login SUCCESS and the login popup closes, the success result does not return to the login page or originator page? This only happens in IE.
The problem is to do with the P3P header required for IE.
We always add this header in our projects (which are MVC3 ASP.NET) by doing this:
protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
base.OnResultExecuting(filterContext);
// You need this to allow IE to have cross domain cookies and sessions
filterContext.HttpContext.Response.AddHeader("P3P:CP", "IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT");
filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", FacebookSettings.CurrentConfig().CanvasUrl);
}
You can find more info here:
Iframe Facebook application and cookies [Internet Explorer]
Found the FB.Event.subscribe('auth.login') not 100% dependable on IE as it sometimes doesn't hit.
When I'm debugging JavaScript in IE it works. When I'm not debugging with IE Developer tool, it usually fails to hit.
I've set a JavaScript time interval as insurance for IE to check FB token received (this works perfectly since I always get the accesstoken after login successfully even though the login event subscribe doesn't work in IE when not debugging).
Still... If anyone know a why to the question, pls feel free to post.
UPDATE
Instead of using the Facebook button that needs to be initialised, I've set up custom anchor/button which calls the log-in function explicitly using JavaScript click event handler. That solves the IE peculiarity and I no longer need a time-interval for checking when the token received. Moreover, I can style it right from the outset, instead of styling over the original FB initialised log-in button.
http://developers.facebook.com/docs/reference/javascript/FB.login/
On the click event, I call:
FB.login(function(response) {
if (response.authResponse) {
//Token, Login Status can be grabbed from response.authResponse
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});