Java示例如何使用OAuth在GAE上使用Facebook帐户登录 [英] Java example how to login with Facebook account on GAE using OAuth

查看:150
本文介绍了Java示例如何使用OAuth在GAE上使用Facebook帐户登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了很多,阅读了许多博客,文章,教程,但直到现在还没有得到一个工作示例,我可以使用面书帐户登录我的应用程序。



我知道我必须使用OAuth,获取令牌,自动生成等...



任何人都可以分享一个例子? (在GAE / JAVA上)

解决方案

这是我如何在App Engine上执行的:



步骤1)在Facebook上注册app(参见 https://developers.facebook。 com / )。你给Facebook一个应用程序的名称和一个url。您注册的网址是您要处理登录页面的网址(jsp或servlet)。从注册你得到两个字符串,一个应用程序ID和一个应用程序秘密(后者是你的密码,不要把它或html写)。



对于这个例子,假设我注册的网址是 http://myappengineappid.appspot.com /signin_fb.do



2)从网页上,用按钮说,您将用户重定向到Facebook上的以下网址,替换您的应用程序id为myfacebookappid在下面的例子。您还必须选择您要求用户的权限(或范围)(参见 https://developers.facebook.com/docs/reference/api/permissions/ )。在这个例子中,我要求访问用户的电子邮件。



(有用的一件事是你可以传递一个可选的字符串,它将不会更改状态参数,例如,我传递用户的数据存储区密钥,所以当Facebook将密钥返回给我时,我可以检索用户,我不这样做)。



这是一个jsp片段:

 <%@ page import =java.net.URLEncoder %GT; 
<%
String fbURL =http://www.facebook.com/dialog/oauth?client_id=myfacebookappid&redirect_uri=+ URLEncoder.encode(http://myappengineappid.appspot。 com / signin_fb.do)+& scope = email;
%>

< a href =<%= fbURL%>>< img src =/ img / facebook.pngborder =0/>< / a& ;

3)您的用户将被转发到Facebook,并要求您批准您要求的权限。然后,用户将被重定向回您已注册的URL。在这个例子中,这是 http://myappengineappid.appspot.com/signin_fb.do 在我的web.xml中映射到以下servlet:

  import org.json.JSONObject; 
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SignInFB扩展HttpServlet {

public void service(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException {
String code = req.getParameter(code );
if(code == null || code.equals()){
//发生错误,处理此
}

String token = null ;
try {
String g =https://graph.facebook.com/oauth/access_token?client_id=myfacebookappid&redirect_uri=+ URLEncoder.encode(http://myappengineappid.appspot.com /signin_fb.do,UTF-8)+& client_secret = myfacebookappsecret& code =+ code;
URL u = new URL(g);
URLConnection c = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine;
StringBuffer b = new StringBuffer();
while((inputLine = in.readLine())!= null)
b.append(inputLine +\\\
);
in.close();
token = b.toString();
if(token.startsWith({))
抛出新异常(请求令牌上的错误+令牌+代码:+代码);
} catch(Exception e){
//发生错误,处理此
}

String graph = null;
try {
String g =https://graph.facebook.com/me? +令牌
URL u = new URL(g);
URLConnection c = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine;
StringBuffer b = new StringBuffer();
while((inputLine = in.readLine())!= null)
b.append(inputLine +\\\
);
in.close();
graph = b.toString();
} catch(Exception e){
//发生错误,处理此
}

String facebookId;
String firstName;
String middleNames;
String lastName;
字符串电子邮件;
性别性别;
try {
JSONObject json = new JSONObject(graph);
facebookId = json.getString(id);
firstName = json.getString(first_name);
if(json.has(middle_name))
middleNames = json.getString(middle_name);
else
middleNames = null;
if(middleNames!= null&& middleNames.equals())
middleNames = null;
lastName = json.getString(last_name);
email = json.getString(email);
if(json.has(gender)){
String g = json.getString(gender);
if(g.equalsIgnoreCase(female))
gender = Gender.FEMALE;
else if(g.equalsIgnoreCase(male))
gender = Gender.MALE;
else
gender = Gender.UNKNOWN;
} else {
gender = Gender.UNKNOWN;
}
} catch(JSONException e){
//发生错误,处理此
}

...

我已经删除错误处理代码,因为您可能想要处理它与我不同。 (此外,性别当然是一个我已经定义的类)。在这一点上,您可以使用任何所需的数据,例如注册新用户或查找现有用户登录。请注意, myfacebookappsecretstring当然应该是你的Facebook的应用程序秘密。



您将需要使用org.json包来使用这个代码,您可以在以下位置找到: a href =http://json.org/java/ =nofollow noreferrer> http://json.org/java/ (只需要.java文件并将它们添加到您的代码中一个org / json文件夹结构)。



我希望这有帮助。如果有什么不清楚,请进行评论,我会更新答案。



Ex animo, - Alexander。



**** UPDATE ****



我想添加一些信息,我的道歉,如果其中一些似乎有点过分。 >

为了能够通过他/她的Facebook帐户登录用户,您需要知道我们正在谈论的数据存储区中的哪个用户。如果它是一个新用户,容易,创建一个新的用户对象(一个名为facebookId的字段,或者你想从Facebook获取的任何东西),将其保存在数据存储中并记录用户。 / p>

如果用户存在,则需要将该字段与facebookId相关联。当用户从Facebook重定向时,您可以抓取facebookId,并查看数据存储区以查找您要登录的用户。



如果您已经有用户,你需要让他们按照你通常的方式登录,所以你知道他们是谁,然后将它们发送到Facebook,然后把facebookId放回去并更新他们的用户对象。这样,他们可以下次使用Facebook登录。



另一个小笔记:用户将在Facebook上显示一个屏幕,要求允许您的应用访问任何你要求的范围,没有办法解决这个问题(你所要求的范围越少,但是似乎越少)。但是,这只会在用户第一次重定向时发生(除非您以后再请求更多的范围,否则会再次询问)。


I searched a lot, read many blogs, articles, tutorials, but until now did not get a working example that I could use face book account to log into my application.

I know that i have to use OAuth, get tokens, autorizations, etc...

Anyone can share a example? (on GAE/JAVA)

解决方案

Here is how I do it on App Engine:

Step 1) Register an "app" on Facebook (cf. https://developers.facebook.com/ ). You give Facebook a name for the app and a url. The url you register is the url to the page (jsp or servlet) that you want to handle the login. From the registration you get two strings, an "app ID" and an "app secret" (the latter being your password, do not give this out or write it in html).

For this example, let's say the url I register is "http://myappengineappid.appspot.com/signin_fb.do".

2) From a webpage, say with a button, you redirect the user to the following url on Facebook, substituting your app id for "myfacebookappid" in the below example. You also have to choose which permissions (or "scopes") you want the ask the user (cf. https://developers.facebook.com/docs/reference/api/permissions/ ). In the example I ask for access to the user's email only.

(A useful thing to know is that you can also pass along an optional string that will be returned unchanged in the "state" parameter. For instance, I pass the user's datastore key, so I can retrieve the user when Facebook passes the key back to me. I do not do this in the example.)

Here is a jsp snippet:

<%@page import="java.net.URLEncoder" %>
<%
    String fbURL = "http://www.facebook.com/dialog/oauth?client_id=myfacebookappid&redirect_uri=" + URLEncoder.encode("http://myappengineappid.appspot.com/signin_fb.do") + "&scope=email";
%>

<a href="<%= fbURL %>"><img src="/img/facebook.png" border="0" /></a>

3) Your user will be forwarded to Facebook, and asked to approve the permissions you ask for. Then, the user will be redirected back to the url you have registered. In this example, this is "http://myappengineappid.appspot.com/signin_fb.do" which in my web.xml maps to the following servlet:

import org.json.JSONObject;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SignInFB extends HttpServlet {

    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {            
        String code = req.getParameter("code");
        if (code == null || code.equals("")) {
            // an error occurred, handle this
        }

        String token = null;
        try {
            String g = "https://graph.facebook.com/oauth/access_token?client_id=myfacebookappid&redirect_uri=" + URLEncoder.encode("http://myappengineappid.appspot.com/signin_fb.do", "UTF-8") + "&client_secret=myfacebookappsecret&code=" + code;
            URL u = new URL(g);
            URLConnection c = u.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
            String inputLine;
            StringBuffer b = new StringBuffer();
            while ((inputLine = in.readLine()) != null)
                b.append(inputLine + "\n");            
            in.close();
            token = b.toString();
            if (token.startsWith("{"))
                throw new Exception("error on requesting token: " + token + " with code: " + code);
        } catch (Exception e) {
                // an error occurred, handle this
        }

        String graph = null;
        try {
            String g = "https://graph.facebook.com/me?" + token;
            URL u = new URL(g);
            URLConnection c = u.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
            String inputLine;
            StringBuffer b = new StringBuffer();
            while ((inputLine = in.readLine()) != null)
                b.append(inputLine + "\n");            
            in.close();
            graph = b.toString();
        } catch (Exception e) {
                // an error occurred, handle this
        }

        String facebookId;
        String firstName;
        String middleNames;
        String lastName;
        String email;
        Gender gender;
        try {
            JSONObject json = new JSONObject(graph);
            facebookId = json.getString("id");
            firstName = json.getString("first_name");
            if (json.has("middle_name"))
               middleNames = json.getString("middle_name");
            else
                middleNames = null;
            if (middleNames != null && middleNames.equals(""))
                middleNames = null;
            lastName = json.getString("last_name");
            email = json.getString("email");
            if (json.has("gender")) {
                String g = json.getString("gender");
                if (g.equalsIgnoreCase("female"))
                    gender = Gender.FEMALE;
                else if (g.equalsIgnoreCase("male"))
                    gender = Gender.MALE;
                else
                    gender = Gender.UNKNOWN;
            } else {
                gender = Gender.UNKNOWN;
            }
        } catch (JSONException e) {
            // an error occurred, handle this
        }

        ...

I have removed error handling code, as you may want to handle it differently than I do. (Also, "Gender" is of course a class that I have defined.) At this point, you can use the data for whatever you want, like registering a new user or look for an existing user to log in. Note that the "myfacebookappsecret" string should of course be your app secret from Facebook.

You will need the "org.json" package to use this code, which you can find at: http://json.org/java/ (just take the .java files and add them to your code in an org/json folder structure).

I hope this helps. If anything is unclear, please do comment, and I will update the answer.

Ex animo, - Alexander.

****UPDATE****

I want to add a few tidbits of information, my apologies if some of this seems a bit excessive.

To be able to log in a user by his/her Facebook account, you need to know which user in the datastore we are talking about. If it's a new user, easy, create a new user object (with a field called "facebookId", or whatever you want to call it, whose value you get from Facebook), persist it in the datastore and log the user in.

If the user exist, you need to have the field with the facebookId. When the user is redirected from Facebook, you can grab the facebookId, and look in the datastore to find the user you want to log in.

If you already have users, you will need to let them log in the way you usually do, so you know who they are, then send them to Facebook, get the facebookId back and update their user object. This way, they can log in using Facebook the next time.

Another small note: The user will be presented with a screen on Facebook asking to allow your app access to whatever scopes you ask for, there is no way around this (the less scopes you ask for, the less intrusive it seems, though). However, this only happens the first time a user is redirected (unless you ask for more scopes later, then it'll ask again).

这篇关于Java示例如何使用OAuth在GAE上使用Facebook帐户登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆