简体   繁体   English

如何将Facebook登录和电子邮件注册添加到我的Google Cloud Endpoints App(Java)?

[英]How do I add both Facebook Login and Email registration to my Google Cloud Endpoints App (Java)?

So I have an app which uses Google App Engine and Google Cloud Endpoints as it's backend in Java. 所以我有一个使用Google App Engine和Google Cloud Endpoints的应用程序,因为它是Java的后端。 I'm currently working on User authentication and here is what I'm trying to do: 我目前正在进行用户身份验证,这是我正在尝试做的事情:

When user first opens the app, they'll have option to either "Login through Facebook" or signup using their email address. 当用户首次打开应用程序时,他们可以选择“通过Facebook登录”或使用他们的电子邮件地址注册。 Then this data would be stored in a user object and after registration would direct them to the app homepage. 然后,这些数据将存储在用户对象中,并在注册后将它们引导到app主页。 It will be saved in their preferences so that they don't need to login every time they open the app (if ever). 它将保存在他们的首选项中,这样他们每次打开应用程序时都不需要登录(如果有的话)。

Now I heard you can use a custom authenticator for Facebook, but there's not much documentation regarding this. 现在我听说你可以使用Facebook的自定义身份验证器,但没有太多关于此的文档。 How can I get the email registration and Facebook Login options to be implemented with Google Cloud Endpoint's Authenticator? 如何通过Google Cloud Endpoint的身份验证器实现电子邮件注册和Facebook登录选项? Or should I make a different approach? 或者我应该采取不同的方法?

Thanks. 谢谢。

My approach is using the Facebook login method (Facebook SDK for Android). 我的方法是使用Facebook登录方法(Facebook SDK for Android)。 The Facebook authentication process returns (on success) an object from which I can get the user's email then I save it in my Endpoints class using Datastore API. Facebook身份验证过程返回(成功时)一个对象,我可以从中获取用户的电子邮件,然后使用Datastore API将其保存在我的Endpoints类中。 To check if user already logged in I chose the SharedPreferences approach with GSON library to parse objects into JSON String and save them in the prefs. 要检查用户是否已登录,我选择了使用GSON库的SharedPreferences方法将对象解析为JSON String并将它们保存在prefs中。

Links and my sample codes below : 链接和我的示例代码如下:

Regarding the Authenticator I found this SO answer 关于认证者,我发现了这个答案

More info about Facebook login method 有关Facebook登录方法的更多信息

Saving custom objects in SharedPreferences 在SharedPreferences中保存自定义对象

Getting user's email through Facebook auth 通过Facebook身份验证获取用户的电子邮件

 private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        if (state.isOpened()) {
            if (isSessionCalled == false) {
                Log.i(TAG, "Logged in...");
                System.out.println("Token=" + session.getAccessToken());

                new Request(
                        session,
                        "/me",
                        null,
                        HttpMethod.GET,
                        new Request.Callback() {
                            public void onCompleted(Response response) {
                                if (response != null) {
                                    GraphObject object = response.getGraphObject();
                                    String email = (String) object.getProperty("email");
                                    Log.i(TAG, "user email : " + email);
                                    String firstName = (String) object.getProperty("first_name");
                                    String lastName = (String) object.getProperty("last_name");
                                    mUserTask = new UserAsyncTask();
                                    mUserTask.execute(email);
                                }

                            }

                        }
                ).executeAsync();

                isSessionCalled = true;
            }
            else {
                Log.w(TAG, "session called twice");
            }

            }

        else if (state.isClosed()) {
            Log.i(TAG, "Logged out...");
        }
    }

Storing the user in my backend : 将用户存储在我的后端:

@ApiMethod(name = "storeUserModel")
    public UserModel storeUserModel(UserModel userModel) throws UserAlreadyExistsException, UserNotFoundException {
        logger.info("inside storeUser");
        String email = userModel.getEmail();
        UserModel checkUser = getUserModel(email);
        logger.info("after getUserModel with email " + email);

        if (checkUser == null) {
            logger.info("inside checkUser is NULL");
            DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
            Transaction txn = datastoreService.beginTransaction();
            try {
                Entity userEntity = new Entity(UserModel.class.getSimpleName(), email);
                userEntity.setProperty("nickname", userModel.getNickname());

                // TODO save the pheromones with the key of userEntity
                datastoreService.put(userEntity);
                txn.commit();
                storePheromoneList(userModel.getPheromoneList(), userEntity.getKey(), datastoreService);
            } finally {
                if (txn.isActive()) {
                    logger.severe("rolled back with email : " +  email);
                    txn.rollback();
                }
            }
        }
        else {
            throw new UserAlreadyExistsException();
        }
        return userModel;

    }

A class that triggers calls to my backend 触发对后端调用的类

public class EndpointsServer implements Server {

    private static final String TAG = "EndpointsServer";

    final UserModelApi userEndpointsApi;

    public EndpointsServer() {
        UserModelApi.Builder builder = new UserModelApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
                .setRootUrl("http://10.0.2.2:8080/_ah/api/")
                .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                    @Override
                    public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                        abstractGoogleClientRequest.setDisableGZipContent(true);
                    }
                });

        userEndpointsApi = builder.build();

    }

    @Override
    public User getUser(String email)  {
        User  user = null;
        try {
            Log.d(TAG, "in getUser with email " +email);
            // get user from db
            UserModel userModel = userEndpointsApi.getUserModel(email).execute();

            if (userModel != null) {
                Log.d(TAG, "user != null with email " + email);
                user = new User(userModel);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return user;
    } 
}

Storing user on successful login : 成功登录时存储用户:

String userString = gson.toJson(user, User.class);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(USER_KEY, userString);
editor.commit();

There's more to it like another client side class to build the api call to the backend and lots of other details. 还有更多就像另一个客户端类来构建对后端的api调用以及许多其他细节。 I can post it if you want. 如果你愿意,我可以发布它。

I can't speak on Java but I started with Python by looking at this repo on Github: https://github.com/loudnate/appengine-endpoints-auth-example 我不能谈论Java,但我开始使用Python,看看Github上的这个回购: https//github.com/loudnate/appengine-endpoints-auth-example

This shows you an example on how to write a custom authenticator with Facebook Login. 这将向您展示如何使用Facebook登录编写自定义身份验证器的示例。 Writing your own authentication I think you should be able to find some examples. 编写自己的身份验证我认为您应该能够找到一些示例。 The only thing you need to do after is to use the same User entity. 您需要做的唯一事情是使用相同的用户实体。

And I suggest you do some reading on how OAUTH 2.0 works so you don't get too confused on the task you need to do. 我建议你阅读OAUTH 2.0如何工作,这样你就不会对你需要做的任务感到困惑。

Basically: 基本上:

  • On your client side, whether web or android, get a facebook access token, sends it to your endpoint service. 在您的客户端,无论是web还是android,获取facebook访问令牌,将其发送到您的端点服务。 Exchange for a access token of your own. 交换您自己的访问令牌。 At the same time, create your User object in datastore and associate the access token. 同时,在数据存储区中创建User对象并关联访问令牌。
  • Then all your subsequent request should use this access token to get access to your endpoint backend. 然后,您的所有后续请求都应使用此访问令牌来访问您的端点后端。 (Do a user check on your endpoint API method.) (用户检查端点API方法。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Java中使用Google Cloud端点引发自定义异常? - How do I raise a custom exception with google cloud endpoints in Java? 如何从服务器端(Google App Engine,Cloud Endpoints)向我的客户端发送信息? - How can I send from the server-side (Google App Engine, Cloud Endpoints) the information to my client? 带有Google Cloud Endpoints的.api文件 - 如何自定义 - .api file with Google Cloud Endpoints - how do I customise 我如何收到 <ArrayList> 使用Google Cloud Endpoints? - How do I receive a <ArrayList> with Google Cloud Endpoints? 如何向Google Cloud端点添加身份验证? - How to add authentication to google cloud endpoints? 如何通过Google Cloud Storage对Java应用程序进行身份验证? - How do I authenticate my Java application with Google Cloud Storage? 在带有Java的Google App Engine中请求云端点的拦截器 - Request Interceptors for Cloud Endpoints in Google App Engine with Java 将 Firebase 应用与 Google Sign In 结合使用时,如何使用我的 Google Cloud Function 进行身份验证? - How do I authenticate with my Google Cloud Function when using my Firebase App with Google Sign In? 如何在Android / IOS应用中通过Google Cloud EndPoints使用基本身份验证(java) - how to use basic authentication in Android/IOS app with Google Cloud EndPoints(java) 如何在App Engine上使用Google Client Library for Java创建Google Cloud Storage可恢复上传网址? - How do I create a Google Cloud Storage resumable upload URL with Google Client Library for Java on App Engine?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM