How can i get access_token and then use it?

泪湿孤枕 提交于 2019-12-06 11:44:37

I actually just got this working in my JSP project! Ok Here is what you need to know. The method you are trying for is called the "Server Side" approach (there is also a Client Side approach which can share a lot of the same code. There are two URLs that you will use (I've wrapped this all into a helper classed I've called FacebookConfig which reads what it needs from a facebook.properties file:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import lombok.Cleanup;
import st.fan.model.users.Listener;

public class FacebookConfig {
  public static String auth_uri;
  public static String id;
  public static String key;

  static{
    Properties properties = new Properties();
    try {
      @Cleanup InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("facebook.properties");
      properties.load(in);
      auth_uri = (String)properties.get("auth_uri");
      id = (String)properties.get("id");
      key = (String)properties.get("key");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static String getOAuthDialogUrl() {
    return "https://www.facebook.com/dialog/oauth?client_id="+id+"&redirect_uri="+auth_uri+"&scope=email";
  }

  public static String getOAuthUrl(String code) {
    return "https://graph.facebook.com/oauth/access_token?client_id="+id+"&redirect_uri="+auth_uri+"&client_secret="+key+"&code="+code;
  }

  public static String getGraphUrl(String token) {
    return "https://graph.facebook.com/me?access_token="+token;
  }

  public static String getProfilePictureUrl(Listener profile) {
    return "https://graph.facebook.com/"+profile.getFacebookId()+"/picture";
  }

  public static String getProfilePictureUrl(Listener profile, String size) {
    return "https://graph.facebook.com/"+profile.getFacebookId()+"/picture?type="+size;
  }
}

Now the user is redirected to the getOAuthDialogUrl() which includes the URL of a servlet called http://example.com/auth/facebook/Auth which has this doGet() method

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
  Transaction tx = null;
  Session dao = SessionFactoryUtil.getInstance().getCurrentSession();
  String redirect = "/auth/facebook/sorry";

  try {
    String code = request.getParameter("code");
    if(code != null) {
      String[] pairs = NetUtils.fetch(new URL(FacebookConfig.getOAuthUrl(code))).toString().split("&");
      String accessToken = null;
      Integer expires = null;
      for (String pair : pairs) {
        String[] kv = pair.split("=");
        if (kv.length == 2) {
          if (kv[0].equals("access_token")) {
            accessToken = kv[1];
          }
          if (kv[0].equals("expires")) {
            expires = Integer.valueOf(kv[1]);
          }
        }
      }
      if(accessToken != null && expires != null) {
        try {
          JSONObject fb_profile = new JSONObject(NetUtils.fetch(new URL(FacebookConfig.getGraphUrl(accessToken))));
          tx = dao.beginTransaction();
          ListenerSession session = authenticate(request, dao);
          if(session == null) {
            session = createSession(response, dao);
          }
          String facebookid = fb_profile.getString("id");
          String name = fb_profile.getString("name");
          String email = fb_profile.getString("email");
          String username = facebookid;
          if(fb_profile.has("username")) {
            username = fb_profile.getString("username");
          }
          Listener user = ListenerDAO.findByFacebookId(facebookid, dao);
          if(user != null) {
            user.setDisplayName(name);
            user.setEmail(email);
            dao.save(user);
          } else {
            user = new Listener();
            user.setUsername(username);
            user.setDisplayName(name);
            user.setEmail(email);
            user.setDateCreated(new DateTime());
            user.setFacebookId(facebookid);
            user.setStatus(ListenerStatus.ACTIVE);
            dao.save(user);
          }
          ListenerSessionDAO.link(session, user, dao);
          redirect = "/";
          tx.commit();
        } catch (JSONException e) {
          log.error("Parsing Facebook Graph Response", e);
        }
      } else {
        log.error("Expected values not found!");
        log.error("accessToken="+accessToken);
        log.error("expires="+expires);
      }
    } else {
      log.error("Missing 'code' param!");
    }
  } catch(Exception e) {
    e.printStackTrace(System.out);
  } finally {
    if(dao.isOpen()) {
      dao.close();
    }
  }
  response.sendRedirect(redirect);
}

And (in addition to using Hibernate, Project Lombok and a simple JSON library called org.json) I use a simple helper function called fetch() which takes a URL and returns the contents as a string which has this code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class NetUtils {
  public static String fetch(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    String line;
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    while((line = reader.readLine()) != null) {
      builder.append(line);
    }
    return builder.toString();
  }
}

This should get you off the ground :)

The facebook authentication guide shows that you should get the token as request parameter. Just don't use response_type=token

just print the $_REQUEST['signed_request'] array and there is oauth in it . that is your active access token use it where you want..

I myself spend two days on it and finally got it

I found a tutorial and it solved my problem. Following is the link of that turorial:

http://pinoyphp.blogspot.com/2010/12/oath-tutorial-how-to-get-facebook.html#comment-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!