2

私のWebアプリケーションでは、ユーザーに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}

前もって感謝します。

4

4 に答える 4

2

私は実際に私のJSPプロジェクトでこれを機能させました! わかりましたここにあなたが知る必要があるものがあります. あなたがしようとしている方法は、「サーバー側」アプローチと呼ばれます (多くの同じコードを共有できるクライアント側アプローチもあります。使用する URL は 2 つあります (これをすべてヘルパーにラップしました)。 facebook.properties ファイルから必要なものを読み取る FacebookConfig を呼び出しました。

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

ユーザーは、この doGet() メソッドを持つhttp://example.com/auth/facebook/Authというサーブレットの URL を含む getOAuthDialogUrl() にリダイレクトされます。

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 ライブラリを使用することに加えて) URL を受け取り、次のコードを持つ文字列としてコンテンツを返す fetch() と呼ばれる単純なヘルパー関数を使用します。

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

これはあなたを地面から離すはずです:)

于 2011-08-23T19:58:24.057 に答える
1

Facebook認証ガイドは、リクエストパラメータとしてトークンを取得する必要があることを示しています。使用しないでくださいresponse_type=token

于 2011-08-23T09:45:05.703 に答える
1

$_REQUEST['signed_request'] 配列を出力するだけで、その中に oauth があります。それはあなたのアクティブなアクセストークンです。必要な場所で使用してください..

私自身、2日間かけてようやく手に入れました

于 2011-09-15T21:48:53.453 に答える
0

チュートリアルを見つけて、問題を解決しました。以下は、そのトゥロリアルのリンクです。

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

于 2011-08-23T13:29:36.187 に答える