【问题标题】:How can i get access_token and then use it?我怎样才能获得 access_token 然后使用它?
【发布时间】:2011-11-01 02:11:15
【问题描述】:

在我的网络应用程序中,我希望用户使用他们的 Facebook 帐户登录。我是通过重定向 url 来实现的。

 response.sendRedirect("http://www.facebook.com/dialog/oauth/?scope=email,user_about_me&dispplay=popup&client_id={app_id}&redirect_uri=http://example.com/index.jsp&response_type=token");

在 index.jsp,我在 url 中获取 access_token。但是在请求中没有访问令牌。我如何在此处获取访问令牌,然后获取用户电子邮件。 index.jsp 中的 url 如下所示:

  http://example.com/index.jsp#access_token={access_token}

提前致谢。

【问题讨论】:

    标签: facebook-graph-api facebook facebook-java-api facebook-java-sdk


    【解决方案1】:

    只需打印 $_REQUEST['signed_request'] 数组,其中就有 oauth。那是您的活动访问令牌,在您想要的地方使用它..

    我自己花了两天时间终于搞定了

    【讨论】:

      【解决方案2】:

      实际上,我刚刚在我的 JSP 项目中使用了这个功能!好的,这是您需要知道的。您正在尝试的方法称为“服务器端”方法(还有一种客户端方法可以共享许多相同的代码。您将使用两个 URL(我已将其全部包装到一个帮助程序中)归类我调用了 FacebookConfig,它从 facebook.properties 文件中读取它需要的内容:

      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;
        }
      }
      

      现在用户被重定向到 getOAuthDialogUrl(),其中包括一个名为 http://example.com/auth/facebook/Auth 的 servlet 的 URL,它具有这个 doGet() 方法

      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);
      }
      

      而且(除了使用 Hibernate、Project Lombok 和一个名为 org.json 的简单 JSON 库之外)我使用了一个名为 fetch() 的简单辅助函数,它接受一个 URL 并将内容作为具有以下代码的字符串返回:

      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();
        }
      }
      

      这应该让你离开地面 :)

      【讨论】:

      • 从哪里可以得到 st.fan.model.users.Listener jar?
      • 在实现了对我发布的stackoverflow.com/questions/5184959/… 的这个问题的答案之后,我得到了这么多,Listener 类基本上就是我谈到的 Profile 类。
      【解决方案3】:

      我找到了一个教程,它解决了我的问题。以下是该教程的链接:

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

      【讨论】:

        【解决方案4】:

        facebook authentication guide 表明您应该获取令牌作为请求参数。只是不要使用response_type=token

        【讨论】:

        • 好的。我使用了 response_type=code。我得到了代码作为请求参数。现在如何获取令牌?
        • pinoyphp.blogspot.com/2010/12/… 我找到了这个教程,但我有点困惑。我得到了代码,但是我怎样才能得到 access_token。如果我尝试将它重定向到其他一些 servlet,那么它会出错。这意味着 request_uri 对于获取代码和 access_token 应该相同。这怎么可能?这就像对同一页面的无限调用。不是吗?
        猜你喜欢
        • 2011-06-04
        • 1970-01-01
        • 2018-03-21
        • 2017-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-05
        • 2023-03-21
        相关资源
        最近更新 更多