Facebook Login verify access token - facebook

I have implemented facebook login and the flow is like below:
The user clicks on Fb login button
I call the FB.login button
Once i get the response.status as connected i call the /me api to
get user details And the done some other stuff
My Point is do i need to validate the access token somewhere in between these steps.
This is how i initialize
FB.init({
appId: 'app_id',
cookie: true,
xfbml: true,
version: 'v2.4'
});

No, you donĀ“t need to verify the token between these steps, you should just handle errors in the callback of FB.api. Also, you can refresh the token for returning users with FB.getLoginStatus, but you should use it on page load only.
Here is a tutorial, if you need more information: http://www.devils-heaven.com/facebook-javascript-sdk-login/

Related

OAuthException when doing a facebook query

I get the following error when trying this URL (just pasting it in a browser to check for output):
https://graph.facebook.com/search?q=London&type=event&access_token=ACCESS_TOKEN
{ "error": {
"message": "(#200) Must have a valid access_token to access this endpoint",
"type": "OAuthException",
"code": 200
}
}
I got the ACCESS_TOKEN by following this guide. What am I doing wrong?
Solution
Thanks to Rahil Arora for the tip. Here is how I printed out my access token:
I put this on my private website. After I set the public URL of the FB app to point to that webpage, I simply clicked on the "login" button. Then there was a popup that allowed my app to access my personal data, and voila! It printed out the access token ;)
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://connect.facebook.net/en_US/all.js"></script>
</head>
<body>
<button id="login">Login to FB</button>
<p>Access token: <span id="token"></span>
<script>
$(function() {
FB.init({
appId : 'APP-ID', // App ID
channelUrl : '', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true
});
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
$('#token').html(response.authResponse.accessToken);
}
});
$('#login').click(function(e) {
FB.login();
});
});
</script>
</body>
</html>
You are using an App Token. What you really need for the request is a User Access Token.
The search API documentation says that:
Searches across page and place objects requires an app access token.
All other endpoints require a user access token.
Since you are searching for an event, you need a User Access Token. You can find more details about generating User Access Tokens here.
To test you queries, you can use the Graph API Explorer. It provides you with a User Access Token by default for testing you queries.
As the error message stated, the provided access token is not valid. If you provide an access token, it must be valid. Otherwise you get an error. If you want read public data w/o any token, leave the access token away entirely.
access token are only valid for a limited period of time. They expire after some time, which can be days or hours. You need to check and ask for a new access token, if it is expired. Usually you get a different and particular error code on this.
The user, which owns the data you want access, must have granted access to your app first. That's how you retrieve the access token by OAauth. Once he revokes this grant, your access token is invalidated. The user can do this at any time w/o your notification, leaving you alone with the above error message.
Bottom line: you need to dig in to that and investigate further what actually has happened:
you actually have an invalid (never valid) token
your token was valid but has been revoked
...

Doubts about Security in Login for Web with Facebook Oauth JavaScript SDK that send ACCESS TOKEN to server

I have doubts about security of my process of authentication oauth with facebook..
I use login for web with javascript sdk with fb button:
I get an Access Token successfully and pass it to server(calling check_facebook_session.php) to make API call to Facebook Provider..
In the following code there is also the log in console of access token.
Everything works!!! on the server I use the php sdk to call the API REST with APPID, APPSECRET and ACCESS_TOKEN:
**
Now my question, have I a security problem?
Is a bad idea to pass the token to the server?
The token that is visible on the client can be used WITHOUT APP SECRET to get information about the user logged?
**
Note: Google+ Sign-In for server-side apps Implementing the one-time-code flow with step:
- Include the Google+ script on your page.
- Add the sign-in button to your page.
- Sign in the user.
- Send the authorization code to the server.
as explained in: https://developers.google.com/+/web/signin/server-side-flow
Unlike facebook google in the js client return a CODE, not an ACCES TOKEN and the server receive and use it to request ACCESS TOKEN.
Thanks..
Following is the javascript code for facebook:
window.fbAsyncInit = function() {
FB.init({
appId : FACEBOOK_APP_ID, // App ID
status : true, // check login status
cookie : false, // enable/disable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response)
{
if (response.status === 'connected')
{
var accessToken = FB.getAuthResponse()['accessToken'];
console.log(accessToken);
$.ajax({
type: 'POST',
url: check_facebook_session.php,
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
processData: false,
data: 'token=' + accessToken,
success: function(result)
{
if(result == 'SUCCESS'){window.location.href = fb_callback_url}
},
error: function(xhr)
{
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
}
});
}
else if (response.status === 'not_authorized')
{
FB.login();
}
else
{
FB.login();
}
});
};
// Load the SDK asynchronously
.......
}(document));
I did some testing and came to the conclusions that I hope can be useful.
In Facebook SDK for JavaScript it automatically handles access token storage and tracking of login status, so apps using it do not need to create their own mechanisms for doing so, and can proceed to making API calls.
The system seems safe because I believe that the callback url of the call is the site that host the page and configured between those of the facebook application, so I can change the application id in the javascript code but the sdk response with error message and get the user's token pretending to be another application. This was already obvious to those who know the flow :-)
Passes the token to the server is definitely a bad idea because it can be snorted and used by simply calling https://graph.facebook.com/me?access_token=... to get user information, In the different flow of google the token is not passed but is passed the code necessary to obtain it.
The best solution to use advantage of client and server is it:
Used in conjunction with the Facebook SDK for JavaScript,
the PHP SDK can share user sessions seamlessly across the client and server.
If people are logged in with Facebook and have authorized your app,
the JavaScript SDK can pick up the user session and persist this in a cookie,
which the PHP SDK reads without any intervention on the developer's part.
To enable this functionality, ensure that when you embed and initialize the JS SDK,
you set both the status and the cookie parameters of the object passed to FB.init() to true.
Regards..
i think it is secure because the user's data is only returned with connected status after user authentication with facebook.
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
I have followed Facebook example on getting access token by using $fb->getJavaScriptHelper();
https://developers.facebook.com/docs/php/howto/example_access_token_from_javascript
$helper = $fb->getJavaScriptHelper();
$accessToken = $helper->getAccessToken();
echo $accessToken->getValue();
P.S. Add try{} catch() {} blocks, as in Facebook example for error handling.

What is the correct setup for the auto-login of a returning, authenticated user with the Javascript SDK?

Hey fellow Facebook developers,
I've read dozens of related questions and hopefully tried every related example on developers.facebook.com but I can't get this one to work:
A user has visited my website and authorized the permissions I request from him via
FB.login(callback, {
scope: 'publish_actions,user_actions:news,user_interests'
});
after calling
FB.init({
appId: 'xxx', // App ID
status: true, // check login status
cookie: true,
xfbml: true // parse XFBML
});
I can now successfully request an access token that is valid for some time and use that to query all kind of information about the user.
Without logging out anywhere (Facebook or my own website), if I now navigate to that page again (or just hit reload), I would expect to immediately be able to use
FB.getLoginStatus(callback)
and receive a response of connected. In my understanding, the user should not have to click anything anymore.
What I do get, though, is unknown. No matter in what browser and no matter whether I am using a real developer profile or a Facebook test user.
I also have subscribed to the events auth.authResponseChange and auth.statusChange but they only fire, if I explicitly call FB.login().
It says in the example in the Facebook SDK documentation that my FB.init() from above should already get the necessary information from Facebook on page load time and that the events should fire accordingly.
Since I tried so many examples already and really think I understand the documentation, I can't see where the error happens.
Is there anything I'm missing, anything I am misunderstanding or a timing problem I should be aware of?
On a side note, I have already tried more than the mentioned Facebook events, a forced status update through FB.getLoginStatus(callback, true), running the code step by step by entering it in the Javascript console of Chrome and more suggestions from SO and Facebook forums.
If you set the status: true, the FB.getLoginStatus response object will be cached by the SDK and subsequent calls to FB.getLoginStatus will return data from this cached response.
To get around this, you have to call FB.getLoginStatus with the second parameter set to true to force a roundtrip to Facebook - effectively refreshing the cache of the response object.
Example:
window.fbAsyncInit = function() {
FB.init({
appId : '',
status : true,
cookie : true,
xfbml : true,
});
FB.getLoginStatus( function(response) {
//console.log(response);
if (response.status === 'connected') {
var accessToken = response.authResponse.accessToken;
alert(accessToken);
} else if (response.status === 'not_authorized') {
//login function
} else {
//login function
}
}, true);
FB.Event.subscribe('auth.authResponseChange', function(response) {
//console.log('The status of the session changed to: '+response.status);
alert(response.status);
});
};
Documentation: https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
As an additional information to Philip's accepted answer, I would like to mention that a cookie blocker was the actual reason the auto-login did not work.
Make sure to disable any plugins you have running before testing your code and assuming "real world" conditions.

Facebook login - access_token

I'm trying to login users to my web page via facebook, and after they login via facebook i want to store their id (and some other informations) in db, so when someone came back, he/she will be redirected to their profile (which script was created first time).
So, i want to ask it is ok to use java sdk (facebook) for getting access token, and then use that token in .php via ajax..
So for example in javascript would be something like this:
FB.init({
appId: 'xxxxxxxxxxx',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
//login
FB.login(function (resp) {
if (resp.authResponse && resp.authResponse.userID) {
var accessToken = response.authResponse.accessToken;
//here will be call for ajax with accessToken parmetar
}
});
});
After that .php (sdk php facebook) will use that access token to get information about user.
Probably you will ask why i dont just send resp.authResponse.userID via ajax and store it in db. Answer is that, someone can use "java in fly" and store users with different id-s. I hope that getting information on .php (server) side with access token will not let this happen..

Permissions on fan page

How do I get permission on an application I have on a fan page tab and stay on the current tab?
I am collecting permissions on the application fine, but when I put the application onto a tab, it goes haywire seemingly getting caught in a never-ending loop and never going anywhere.
You could do this with the JavaScript SDK:
//Facebook connection with the JavaScript SDK
FB.init({
appId: 'YOURAPPID',
cookie: true,
xfbml: true,
status: true });
FB.getLoginStatus(function (response) {
//If you have permissions already
if (response.session) {
//Do application stuff...
}
else {
//Redirect browser to the permission dialogue
top.location="https://www.facebook.com/connect/uiserver.php?app_id=YOURAPPID&method=permissions.request&display=page&next=REDIRECTPAGEURI&response_type=token&fbconnect=1&perms=email,read_stream,publish_stream,offline_access";
}
});
You put in your application ID in the fb.init function, and then adjust the redirect for the permissions dialogue so it includes your application ID, the URI you want to re-direct to after the user accepts the permission dialogue, and finally the permissions you want to get (in this case I included email, read stream, publish stream and offline access token).