RestFB: Using a facebook app to get the users Access Token

Bevilacqua picture Bevilacqua · Dec 2, 2012 · Viewed 18.6k times · Source

This is what i have:

static AccessToken accessToken = new DefaultFacebookClient().obtainExtendedAccessToken("<my app id>", "<my app secret>");
static FacebookClient client = new DefaultFacebookClient();
public static void main(String args[]) {
    System.out.print("Enter Your Status: ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String status= null;

      try {
         userName = br.readLine();
         System.out.println("..........");
      } catch (IOException ioe) {
         System.out.println("!");
         System.exit(1);
      }

    FacebookType publishMessageResponse =
                client.publish("me/feed", FacebookType.class,
                Parameter.with("message", status));

So first line gets the token and stores it as type AccessToken but what good does that do to me because next line i need to provide the access token as a string and i can't convert it. Any Help?

Answer

Val picture Val · Aug 9, 2013

First of all don't confuse app token with user token (more info)

To get user token you have to

  1. Provide a way for user to authenticate against Facebook (more info) and receive "code" - an encrypted string unique to each login request.
  2. Get the user token using this code.

You can get user token with pure RestFB the following way:

private FacebookClient.AccessToken getFacebookUserToken(String code, String redirectUrl) throws IOException {
    String appId = "YOUR_APP_ID";
    String secretKey = "YOUR_SECRET_KEY";

    WebRequestor wr = new DefaultWebRequestor();
    WebRequestor.Response accessTokenResponse = wr.executeGet(
            "https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&redirect_uri=" + redirectUrl
            + "&client_secret=" + secretKey + "&code=" + code);

    return DefaultFacebookClient.AccessToken.fromQueryString(accessTokenResponse.getBody());
}

The call is simple:

FacebookClient.AccessToken token = getFacebookUserToken(code, redirectUrl);
String accessToken = token.getAccessToken();
Date expires = token.getExpires();