How to retrieve the facebook oauth 2.0 access_token - facebook

I am trying to get the access_token of the logged in facebook user.
I get something like this.. url followed by the code i am retrieve the code..
it says in the guide to exchange it for access_token...
https://graph.facebook.com/oauth/access_token?
client_id=XXXXXXXXXXXXXX&
redirect_uri=http://www.my-site.com/&
client_secret=XXXXXXXXXXXXXXXXXXXXX&
code=2.hJFWoMlLf3tLOSos_qNCBg__.3600.1279836000-10000100XXXXXXX|kGwPB4y5K_-ijD9_1CfjSpT-oaY..
How i can exchange it for a access_token using what FB.api or jquery or javascript..
When i plug this url in the address bar.. i am able to see access_token..
I appreciate if somebody can tell me how to retrieve the access_token using javascript or jquery.
Thanks.

According to Facebook, and my personal experiences with the api, the FB.getSession() function is deprecated and should throw an exception if called.
From facebook:
The FB.getAuthResponse method is a replacement for the FB.getSession method which was deprecated after the migration to OAuth 2.0.
Instead you should use the getLoginStatus callback -
FB.getLoginStatus(function(response) {
var token = response.authResponse.accessToken;
});
//Example structure of response object
var eg =
{
status: 'connected',
authResponse: {
accessToken: '...',
expiresIn:'...',
signedRequest:'...',
userID:'...'
}
};
source: http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

If you are using the JavaScript SDK, then after logging in the user, getting the access token in your JavaScript code is as simple as:
FB.getSession().access_token
However, getSession may return null if a user is logged out, so the proper way is to first check for null before accessing the token.
var session = FB.getSession();
if(session != null) { // user is still logged in
console.log(session.access_token);
}

Related

Ember Torii facebook authentication not able to get user email

I am using Ember CLI + ember simple auth torii link
to get authentication code from facebook for my ember app.
This is my environment.js file
ENV['torii'] = {
providers: {
'facebook-oauth2': {
apiKey: '865549306850377',
scope: 'email',
//redirectUri: window.document.location.href
redirectUri: 'http://localhost:4200/'
}
}
};
And my login controller looks like this -
facebook: function() {
var _this = this;
this.get('session').authenticate('simple-auth-authenticator:torii', 'facebook-oauth2').then(function(data){
console.log("status - ", _this.get('session'));
});
}
And login.hbs -
<li><button {{action "facebook" "facebook-oauth2"}}>Facebook OAuth2</button></li>
After the user clicks on the link, a facebook popup opens and ember app gets a token.
How do I get the user's email id along with this token ?
Has anybody faced a similar issue ?
So you're using oauth2, so all you're ever going to get is an authorization token. With this token, you can then go off and request other information. The token is basically just there to speed up the validation of users against your application.
If you want to get user information, you would need to create another method (probably on your server-side), which swaps the authorization code for an access token: like so (or alternatively you can request an access token directly, which would remove the need for a server-side solution.
Using the access Token you can then request the Facebook User ID, using the debug token endpoint, and after that you will be able get to any endpoint to get the information you need.

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.

Should I pass access token when using FB.api()?

I'm just a little confused as to how to pass my access token into FB.api() when making requests for protected things.
I'm getting my app to login and authenticate fine, but how do I use FB.api() with the access token I have?
app.accessToken = response.authResponse.accessToken; // This is a valid access token.
FB.api('/me/friends?access_token='+app.accessToken, {fields: 'name,id,location,picture,installed'}, function(response) {
console.log(response);
});
Is that the correct way to pass in the access token to FB.api()?
In this case, my response comes back with the friends name,id,location,picture but it doesn't seem to have the 'installed' data as that is protected.
Am I doing this right?
Although I see why some users are saying you may not need to pass access token due to your specific use.
Generally, there are cases where you do need to pass an access token through FB.api()
The way this is done is by passing it in the parameter object, as such:
FB.api('/{fb-graph-node-goes-here}/, {
access_token: "TOKEN GOES HERE"
//other parameters can go here aswell
}, function(response) {
console.log(response);
});
You do not need to pass the token, if the user logged in (with FB.login, for example). In fact, by using the JavaScript SDK (or PHP SDK), you almost never need to deal with the (user) access tokens.
So, your call would just be like this:
FB.api('/me/friends', function(response) {
console.log(response);
});
Getting the info if the user installed the app:
Test if user has application installed with Graph API
How to fetch a list of the current users' friends who also use my app?
That is how I did it:
Pass access_token as a parameter.
FB.api("/me", { access_token : response.authResponse.accessToken }, {fields: ['last_name', 'first_name', 'name']},
function (response) {
console.log(response);
console.log('Name: ' + response.name);
}
);
You would need to pass access token if requesting for extending fields. Please refer to
https://developers.facebook.com/docs/facebook-login/permissions/v2.0#reference-extended-profile

Different Facebook access token JavaScript SDK

I'm quite confused with the access token from facebook..here is how I obtain the user's access token and use it to get data from graph API
window.fbAsyncInit = function() {
FB.init({
appId : 'app ID',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.getLoginStatus(getStatus);
FB.Event.subscribe('auth.authResponseChange', getStatus);
function getStatus(response) {
if ( response.status === 'connected' ) {
var accessToken = response.authResponse.accessToken;
console.log("accessToken = " + accessToken);
$.ajax({
dataType : "jsonp",
type : "GET",
url : "https://graph.facebook.com/me/albums?access_token=" + accessToken,
success : function(data) {
$.each(data, function(index, value) {
console.log(index + ": " + value);
})
}
});
}
}
};
However, I always get an empty data. After I visit the graph API documentation here: https://developers.facebook.com/docs/reference/api/ and click on one of the graph links, I notice that the access token generated there is always different from what I retrieve from my code. For example, the current access token in the graph api documentation is
"AAAAAAITEghMBAMwuyHZCO3VOAvCm9hHpaZC9PGV9238ixsZB7zSfuplZBTZCLRj6cEViZADJlVcjOfInwvcbhqu3XBF1w4ZAxvPbexcGQZAYzb4bHAKsMbLF"
and the one in console log is
"AAAG0ZCFantJ8BAAFcMdDOyDyT4OBtjrvULEaS2o94gZAU7U1xITaogFXCZBghQP8G9bjEh3XSCATQOZCUSZCuNWFvEfypIAmcz9bkbk5qRBlHUZAOE4guW"
I think that I may have done this the wrong way. Can anyone help explain to me how to retrieve data from graph API in a correct way?
Any kinds of help will be appreciated. Thanks in advance :)
Run this URL with your authToken first:
https://graph.facebook.com/me/permissions?access_token=USER_ACCESS_TOKEN
You'll almost certainly only see basic permissions in the response, which is why you aren't getting the data from your call to the user's album.
You'll then want to run your user through the Authentication Process, making sure you request the permissions you need (probably 'user_photos' in your case).
More info is available in those two links. Good luck!
access token will never be the same. So that behaviour is correct.
Back to your problem , I think its mostly scope related issue.
I had developed a application using facebook c# sdk, In that application i did it like this:
when a post is to be submitted , redirect the user to facebook (with some parameters like appid, app-secret, auth-token and
redirect-url);
Facebook will ask the user to login with his credentials.
When the user is logged in, facebook will redirect back to the redirect-url. (with the authtoken and a new auth-code).
Then we should use this auth-code, app-id and app-secret and obtain the user-access-token. (This is done by doing a rest api call to the
url
https://graph.facebook.com/oauth/access_token?client_id=client_id&redirect_uri=redirect_uri&client_secret=client_secret&code=auth-code
This will return the user-token and expiry time for the token
And then we can post using this user-access-token to the fb.
Initially i had misunderstood the auth-code and used it as the user-access-token, and i always got the result as unauthorised token .
Please check whether this will help you or not.

Reusing Access_Token from server in Facebook JS SDK

I am using Facebook c# SDK to authenticate user (successfully). But I want also to use FB.ui JS methods on client. Is there any way to "reuse" already received access_token from c# SDK in Facebook JS SDK? I don't want to call FB.Login because I've already authenticated user on server side.
Just put the access_token string to a hidden field and get the value through javascript and pass it to the JS API Methods.
FB.getLoginStatus(function(response) {
if (response.authResponse) {
fbUserId = response.authResponse.userID;
token = response.authResponse.accessToken;
} else {
fbUserId = 0;
}
});
you will get access token