I’m building a form and want to fetch fields like “first_name” and “last_name” by e.g. facebook or google data but only receive an object with every entry is “null”
I’ve tryed go add a custom ScropeBuilder, fetching different accounts.
my application is only giving the access-token to the browsers terminal so I can send a request via postman to get the data i want.
tokencontroller:
package com.example.demo;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Version;
import com.restfb.scope.FacebookPermissions;
import com.restfb.scope.ScopeBuilder;
import com.restfb.types.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.FacebookProfile;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value="/tokencontroller")
public class TokenController {
@Autowired
Facebook facebook;
@Autowired
ConnectionRepository connectionRepository;
@RequestMapping(value = "/userdata/{accessToken}", method = RequestMethod.POST)
public UserModel userMod(@PathVariable(value = "accessToken") String accessToken) {
UserModel userModel = new UserModel();
ScopeBuilder scopeBuilder = new ScopeBuilder();
scopeBuilder.addPermission(FacebookPermissions.PUBLIC_PROFILE);
/*if(connectionRepository.findPrimaryConnection(Facebook.class) == null) {
return null;
}*/
System.out.println("n n n accesstoken: "+accessToken);
FacebookClient fbClient = new DefaultFacebookClient(accessToken, Version.VERSION_4_0);
User user = fbClient.fetchObject("me",User.class);
System.out.println("User: "+user);
System.out.println("Firstname: "+user.getFirstName());
return userModel;
}
@RequestMapping(value = "/getURL")
public void getUrl(){
ScopeBuilder scopeBuilder = new ScopeBuilder();
scopeBuilder.addPermission(FacebookPermissions.PUBLIC_PROFILE);
FacebookClient client = new DefaultFacebookClient(Version.LATEST);
String url = client.getLoginDialogUrl("502780177145376","/connect/facebook",scopeBuilder);
System.out.println(url);
}
}
```
facebookConnect.html
```HTML
<!DOCTYPE html >
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8"/>
<script src="scripts/facebookSDK.js"></script>
</head>
<body>
<h1>lala land</h1>
<!--
Below we include the Login Button social plugin. This button uses
the JavaScript SDK to present a graphical Login button that triggers
the FB.login() function when clicked.
-->
<script>
// 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.
testAPI();
} else {
// The person is not logged into your app or we are unable to tell.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '502780177145376',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v4.0' // The Graph API version to use for the call
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// 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 = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me',{"fields":"first_name"}, function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
}
function login(){
FB.login(function(response){
console.log("n Response: "+response.connectionState);
try{
if(response == 'connected')
console.log("Connected: "+true);
else{
console.log("not connected");
console.log("accesstoken: " + response.authResponse.accessToken);
}}
catch (e) {
console.log(e);
console.log("is nich");
}
});
}
</script>
<button onclick="login()">Login Button</button>
<div id="status">
</div>
</body>
</html>
```
I expect the output to be:
```JSON
{
"firstName": John,
"lastName": Johnson,
"address": myAddress,
"birthDay": myBirthday,
"email": myEmail,
"gender": myGender
}
```
Actual output is:
```JSON
{
"firstName": null,
"lastName": null,
"address": null,
"birthDay": null,
"email": null,
"gender": null
}
```
When logging it in console there is no exception or error message, just:
```
accesstoken: EAAHJRqHb3iABAEyFblVBaOAaEjbsw8q4cNSQsQuFbSI40r3GZAAZBMe6e0VZCrNX1I8L16VZAeWVZALrws0AmcLFZCgcuJHyRB3briOYS7QKCm3T7fIi3WZBsAngtIpDlewm14ZCIq66FMtZB5ZChZBkNUciwcpJJ3f0ZAuvcYozEZANAZB3KIuY7KKmHdnaVj5vkSdL0NlgAnZBrBcsZAZBp6NZBeUygz
User: User[about=null ageRange=null bio=null birthday=null birthdayAsDate=null context=null cover=null currency=null devices=[] education=[] email=null favoriteAthletes=[] favoriteTeams=[] firstName=null gender=null hometown=null hometownName=null id=111826290166761 idsForApps=[] idsForBusiness=[] idsForPages=[] inspirationalPeople=[] installType=null installed=null interestedIn=[] invitableFriends=[] isSharedLogin=null isVerified=null labels=[] languages=[] lastName=null likes=null link=null locale=null location=null meetingFor=[] metadata=null middleName=null name=John Johnson nameFormat=null paymentPricepoints=null picture=null political=null publicKey=null quotes=null relationshipStatus=null religion=null securitySettings=null sharedLoginUpgradeRequiredBy=null shortName=null significantOther=null sports=[] testGroup=null thirdPartyId=null timezone=null tokenForBusiness=null type=null updatedTime=null username=null verified=null videoUploadLimits=null viewerCanSendGift=null website=null work=[]]
Firstname: null```
I don't get why it's not fetching the correct userdata.
May anyone can help me?
You can check it out at github if u want to: https://github.com/rosariop/FacebookSpringboottest2
2
Answers
If you want to fetch user details through access-token you need to generate an access token with proper configuration, kindly refer the following screen for the same
all specific information needs to be included while generating access token
You have specify which fields you need.
So the line
needs to be changed to
The fields parameter is added to the query and you get exactly these fields of the requested object (and ID).