I am trying to get the lastname of my profile using restfb.But but each time the username is returned as null.I already have the acess token and permissions.I guess t some problem with the JSon object passing.how can i pass the json objects to a javabean and later retrieve it?
This happens when the access token you provided doesn't have the correct permissions to access the data. Best way to check this is by using the facebook graph API interface; noting the version.
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=me&version=v2.4
FacebookClient fbClient = new DefaultFacebookClient(accessToken, Version.VERSION_2_4);
User me = fbClient.fetchObject("me", User.class, Parameter.with("fields", "email,first_name,last_name,gender"));
Note: Your FB.login function must contain the correct scope for fields you want to access.
FB.login(function(response) {
...
}, {scope: 'email'});
This works for me:
FacebookClient facebookClient = new DefaultFacebookClient(MY_ACCESS_TOKEN);
User user = facebookClient.fetchObject("me", User.class);
out.println("Last name: " + user.getLastName());
Here is the code snippet
FacebookClient facebookClient = new DefaultFacebookClient("register a facebook application with required permissions, get that application token and paste here");
User user = facebookClient.fetchObject("me", User.class);
Connection<User> myFriends = facebookClient.fetchConnection("me/friends", User.class);
for(User friend:myFriends.getData())
{
Connection<Page> myMovies = facebookClient.fetchConnection(friend.getId() + "/movies", Page.class);
content = content + "Name: " + friend.getName();
for(Page page:myMovies.getData())
{
content = content + "\n" + "Movies: " + page.getName() + "\n";
}
}
In this example your application needs "friends_likes" permission.
Hope this helps.
Related
I have a Java application that integrates with One Drive through Microsoft Graph. I followed the documentation and I am able to pass the authorisation step but when interrogating the API I get this error:
"AADSTS70000121: The passed grant is from a personal Microsoft account and is required to be sent to the /consumers or /common endpoint."
What am I missing?
This is the code I am using:
Get an authorisation token using the URL bellow
private static final String RESPONSE_TYPE = "code";
private static final String SCOPE = "openid%20Files.Read%20Files.ReadWrite%20Contacts.Read%20offline_access";
String authorizeUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=" + CLIENT_ID
+ "&scope=" + SCOPE + "&response_type=" + RESPONSE_TYPE + "&redirect_uri=" + REDIRECT_URL;
Exchange the received authorization token
List<String> scopes = new LinkedList<String>();
scopes.add("https://graph.microsoft.com/.default");
AuthorizationCodeCredential authCodeCredential = new AuthorizationCodeCredentialBuilder()
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.authorizationCode(authorizationCode)
.redirectUrl(REDIRECT_URL)
.build();
TokenCredentialAuthProvider tokenCredAuthProvider = new TokenCredentialAuthProvider(scopes, authCodeCredential);
GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider(tokenCredAuthProvider).buildClient();
User me = graphClient.me()
.buildRequest()
.get();
As you are using the personal account then please change the endpoint to consumers instead of common,
https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?
ref doc - https://learn.microsoft.com/en-au/azure/active-directory/develop/v2-oauth2-auth-code-flow
Hope this helps
Thanks
I'm trying to use the Authentication::login() API call in the DocuSign Java SDK and am receiving an error. Here's some code:
#Component
public class TestClass {
private ApiClient apiClient;
public void authenticate() {
this.apiClient = new ApiClient("account-d.docusign.com", "docusignAccessCode",
"mySecretIntegratorKey", "myClientSecret");
final AuthenticationApi authenticationApi = new AuthenticationApi(this.apiClient);
try {
// ERROR ON THE LINE BELOW
final LoginInformation loginInformation = authenticationApi.login();
} catch (final ApiException e) {
// do something appropriate
}
}
}
The mySecretIntegratorKey and myClientSecret values are not the real values I'm sending in obviously, but the other ones are.
Here is the error I am receiving when making the login() call:
Caused by: org.apache.oltu.oauth2.common.exception.OAuthSystemException: Missing grant_type/code
at com.docusign.esign.client.auth.OAuth$OAuthJerseyClient.execute(OAuth.java:184)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:65)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:55)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:71)
at com.docusign.esign.client.auth.OAuth.updateAccessToken(OAuth.java:92)
... 123 common frames omitted
I realize that this is using the older legacy authentication, however I have a limitation that won't allow me to upgrade to the newer method of authentication until the first of the year. So for now I need to use this legacy method using SDK Version 2.2.1.
Any ideas what I'm doing wrong here? I'm sure it is something simple...
Thank you for your time.
You want to use Legacy authentication?
In that case you need to make a number of updates to your code.
Only call new ApiClient(base_url)
Set the X-DocuSign-Authentication header--
From an old Readme:
String authHeader = "{\"Username\":\"" + username +
"\",\"Password\":\"" + password +
"\",\"IntegratorKey\":\"" + integratorKey + "\"}";
apiClient.addDefaultHeader("X-DocuSign-Authentication", authHeader);
Then use the authenticationApi.login to look up the user's Account ID(s) and matching base urls.
The authenticationApi.login doe not actually log you in. (!)
Rather, that method just gives you information about the current user.
There is no login with the API since it does not use sessions. Instead, credentials are passed with every API call. The credentials can be an Access Token (preferred), or via Legacy Authentication, a name / password / integration key triplet.
When using Legacy Authentication, the client secret is not used.
More information: see the Readme section for using username/password in this old version of the repo.
Just in case someone was looking for complete legacy code that works! The below C# code snippet works. This is production ready code. I've tested it and it works. You will have to create an EnvelopeDefinition separately as this code is not included. However, the piece below will authenticate the user and will successfully send an envelope and get back the Envelope ID:
string username = "john.bunce#mail.com";
string password = "your_password";
string integratorKey = "your_integration_key";
ApiClient apiClient = new ApiClient("https://www.docusign.net/restapi");
string authHeader = "{\"Username\":\"" + username + "\", \"Password\":\"" + password + "\", \"IntegratorKey\":\"" + integratorKey + "\"}";
apiClient.Configuration.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
AuthenticationApi authApi = new AuthenticationApi(apiClient.Configuration);
LoginInformation loginInfo = authApi.Login();
string accountId = loginInfo.LoginAccounts[0].AccountId;
string baseURL = loginInfo.LoginAccounts[0].BaseUrl;
string[] baseUrlArray= Regex.Split(baseURL, "/v2");
ApiClient apiClient2 = new ApiClient(baseUrlArray[0]);
string authHeader2 = "{\"Username\":\"" + username + "\", \"Password\":\"" + password + "\", \"IntegratorKey\":\"" + integratorKey + "\"}";
apiClient2.Configuration.AddDefaultHeader("X-DocuSign-Authentication", authHeader2);
EnvelopesApi envelopesApi = new EnvelopesApi(apiClient2.Configuration);
EnvelopeSummary results = envelopesApi.CreateEnvelope(accountId, envelopeDefinition);
string envelopeID = results.EnvelopeId;
I am trying to post a message onto a facebook group (I am the admin for the page). Here is the java code that I am using:
public void makeTestPost() {
fbClient = new DefaultFacebookClient(groupPageAccessToken);
counter = 0;
fbClient.publish(groupID + "/posts", FacebookType.class, Parameter.with("message", Integer.toString(counter) + ": Hello, fb World!"));
counter++;
}
with:
private final string groupPageAccessToken = "XXXXXXXXXXXXXXXXXX";
private final String groupID = "XXXXXXX";
I got these values using the facebook graph explorer api online Graph API Explorer
But when I login to facebook I don't see any message/post on the group. Please tell me how to make it work?
You need an user access token with the permissions publish_actions and user_managed_groups.
Then you can publish a new message like this:
GraphResponse response = fbClient.publish(groupID + "/feed", GraphResponse.class, Parameter.with("message", Integer.toString(counter) + ": Hello, fb World!"));
Recently I've been struggling with getting user information from post_id with java. I'm new in restfb, but after reasearching, below code should work. All available permissions are granted. Even in Graph API Explorer when writing post_id I cannot retrieve post's author details.
This is how I do it:
FacebookClient facebookClient = new DefaultFacebookClient(token);
String command = "orangepolska/feed";
Connection<Post> pagePosts = facebookClient.fetchConnection(command, Post.class);
ArrayList<String> postList = new ArrayList<String>();
String row;
for( List<Post> posts : pagePosts){
for (Post post : posts) {
if (post.getCreatedTime().after(startDate) && post.getCreatedTime().before(endDate)){
String message = post.getMessage();
CategorizedFacebookType postedBy = post.getFrom();
Post.Comments comments = post.getComments();
row = " owner: "+postedBy.getName()+" owner_id: "+postedBy.getId()+" post: "+message+" + " likes: "+post.getLikesCount() + "\n";
System.out.println(row);
postList.add(row);
}
}
}
return postList;
The problem occurs with various of functions like: getName(), getID(), getLikesCount() etc - these return null.
How can i fix it?
Thanks in advance.
You need to fetch the feed with the fields parameter so Facebook knows which fields you need to be filled. RestFB can only provide access to information that are given by Facebook ;)
Have a look here: http://restfb.com/#selecting-specific-fields
Norbert is correct but the link he posted did not work for me - you need to include "Parameter.with("fields", "from")" to get the user information.
Connection<Post> pagePosts = facebookClient.fetchConnection(command, Post.class, Parameter.with("fields", "from"));
I'm looking for a was to get the groupId. To be more specific, I want to get the site ID of a community or organisation when a user signs in so I can redirect the user to the right "site".
I tried looking into PortalUtil in Liferay's documentation but it doesn't offer an easy function to get that ID.
I also tried ThemeDisplay but that only works for portlets.
Here is an excerpt from a LoginPostAction in hook which serves your needs.
User user = PortalUtil.getUser(request);
List<Organization> orgList = OrganizationLocalServiceUtil.getUserOrganizations(user.getUserId());
for (Organization org : orgList) {
String orgFriendlyURL = org.getGroup().getFriendlyURL();
.
.//some custom code
.
String myPath = "/" + language + "/group" + orgFriendlyURL + "/home";
LastPath lastPath = new LastPath(StringPool.BLANK, myPath);
HttpSession session = request.getSession();
session.setAttribute(WebKeys.LAST_PATH, lastPath);
_log.debug("Last Path for current User[" + user.getScreenName() + "] is : " + lastPath);
break;
}