热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何使用FirebaseAuth从Google提供商处获得性别和生日?

如何解决《如何使用FirebaseAuth从Google提供商处获得性别和生日?》经验,为你挑选了1个好方法。

我正在尝试使用Firebase AuthUI从Google提供商处获得性别和生日.这是我的代码.

AuthUI.IdpConfig googleIdp = new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER)
                .setPermissions(Arrays.asList(Scopes.EMAIL, Scopes.PROFILE, Scopes.PLUS_ME))
                .build();

startActivityForResult(
                AuthUI.getInstance().createSignInIntentBuilder()
                        .setLogo(R.drawable.firebase_auth_120dp)
                        .setProviders(Arrays.asList(
                new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                googleIdp))
                        .setIsSmartLockEnabled(false)
                        .setTheme(R.style.AppTheme_Login)
                        .build(),
                RC_SIGN_IN);

在onActivityResult中:

IdpResponse idpRespOnse= IdpResponse.fromResultIntent(data);

我有idpResponse,但它只包括idpSecretidpToken.如何访问性别和生日等个人资料的其他请求字段?我可以访问公共领域的电子邮件,姓名,照片等

FirebaseAuth.getInstance().getCurrentUser();

Sabeeh.. 8

Firebase不支持,但您可以通过以下方式执行此操作:

首先,您需要client_idclient_secret.

您可以按照以下步骤从Firebase面板获取这两个:

认证 >> 登录方法.单击Google并展开Web SDK配置.

Gradle依赖项:

compile 'com.google.apis:google-api-services-people:v1-rev63-1.22.0'

在登录活动中添加以下方法.

    private void setupGoogleAdditionalDetailsLogin() {
                // Configure sign-in to request the user's ID, email address, and basic profile. ID and
                // basic profile are included in DEFAULT_SIGN_IN.
                GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestEmail()
                        .requestIdToken(GOOGLE_CLIENT_ID)
                        .requestServerAuthCode(GOOGLE_CLIENT_ID)
                        .requestScopes(new Scope("profile"))
                        .build();

        // Build a GoogleApiClient with access to GoogleSignIn.API and the options above.
                mGoogleApiClient = new GoogleApiClient.Builder(this)
                        .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                            @Override
                            public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                                Log.d(TAG, "onConnectionFailed: ");
                            }
                        })
                        .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                        .build();
            }

     public void googleAdditionalDetailsResult(Intent data) {
            Log.d(TAG, "googleAdditionalDetailsResult: ");
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Signed in successfully
                GoogleSignInAccount acct = result.getSignInAccount();
                // execute AsyncTask to get data from Google People API
                new GoogleAdditionalDetailsTask().execute(acct);
            } else {
                Log.d(TAG, "googleAdditionalDetailsResult: fail");
                startHomeActivity();
            }
        }

    private void startGoogleAdditionalRequest() {
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            startActivityForResult(signInIntent, RC_SIGN_GOOGLE);
        }

异步任务以获取其他详细信息

public class GoogleAdditionalDetailsTask extends AsyncTask {
        @Override
        protected Person doInBackground(GoogleSignInAccount... googleSignInAccounts) {
            Person profile = null;
            try {
                HttpTransport httpTransport = new NetHttpTransport();
                JacksonFactory jsOnFactory= JacksonFactory.getDefaultInstance();

                //Redirect URL for web based applications.
                // Can be empty too.
                String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";

                // Exchange auth code for access token
                GoogleTokenResponse tokenRespOnse= new GoogleAuthorizationCodeTokenRequest(
                        httpTransport,
                        jsonFactory,
                        GOOGLE_CLIENT_ID,
                        GOOGLE_CLIENT_SECRET,
                        googleSignInAccounts[0].getServerAuthCode(),
                        redirectUrl
                ).execute();

                GoogleCredential credential = new GoogleCredential.Builder()
                        .setClientSecrets(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET)
                        .setTransport(httpTransport)
                        .setJsonFactory(jsonFactory)
                        .build();

                credential.setFromTokenResponse(tokenResponse);

                People peopleService = new People.Builder(httpTransport, jsonFactory, credential)
                        .setApplicationName(App.getInstance().getString(R.string.app_name))
                        .build();

                // Get the user's profile
                profile = peopleService.people().get("people/me").execute();
            } catch (IOException e) {
                Log.d(TAG, "doInBackground: " + e.getMessage());
                e.printStackTrace();
            }
            return profile;
        }

        @Override
        protected void onPostExecute(Person person) {
            if (person != null) {
                if (person.getGenders() != null && person.getGenders().size() > 0) {
                    profileGender = person.getGenders().get(0).getValue();
                }
                if (person.getBirthdays() != null && person.getBirthdays().get(0).size() > 0) {
//                    yyyy-MM-dd
                    Date dobDate = person.getBirthdays().get(0).getDate();
                    if (dobDate.getYear() != null) {
                        profileBirthday = dobDate.getYear() + "-" + dobDate.getMonth() + "-" + dobDate.getDay();
                        profileYearOfBirth = DateHelper.getYearFromGoogleDate(profileBirthday);
                    }
                }
                if (person.getBiographies() != null && person.getBiographies().size() > 0) {
                    profileAbout = person.getBiographies().get(0).getValue();
                }
                if (person.getCoverPhotos() != null && person.getCoverPhotos().size() > 0) {
                    profileCover = person.getCoverPhotos().get(0).getUrl();
                }
                Log.d(TAG, String.format("googleOnComplete: gender: %s, birthday: %s, about: %s, cover: %s", profileGender, profileBirthday, profileAbout, profileCover));
            }
            startHomeActivity();
        }
    }

改变你onActivityResult像这样:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_GOOGLE) {    // result for addition details request
            googleAdditionalDetailsResult(data);
            return;
        } else if (requestCode == RC_SIGN_IN && resultCode == RESULT_OK) {  //logged in with firebase
            if (FirebaseAuth.getInstance().getCurrentUser().getProviders().get(0).equals("google.com")) {
            // user logged in with google account using firebase ui
                startGoogleAdditionalRequest();
            } else {
            // user logged in with google
                startHomeActivity();
            }
        } else {
            // handle error
        }
    }

更新:如果代码出错

personFields掩码是必需的

然后使用以下代码:

profile = peopleService.people().get("people/me"). setRequestMaskIncludeField("person.names,person.emailAddress??es,person.genders,pe??rson.birthdays").exe??cute();

谢谢@AbrahamGharyali.



1> Sabeeh..:

Firebase不支持,但您可以通过以下方式执行此操作:

首先,您需要client_idclient_secret.

您可以按照以下步骤从Firebase面板获取这两个:

认证 >> 登录方法.单击Google并展开Web SDK配置.

Gradle依赖项:

compile 'com.google.apis:google-api-services-people:v1-rev63-1.22.0'

在登录活动中添加以下方法.

    private void setupGoogleAdditionalDetailsLogin() {
                // Configure sign-in to request the user's ID, email address, and basic profile. ID and
                // basic profile are included in DEFAULT_SIGN_IN.
                GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestEmail()
                        .requestIdToken(GOOGLE_CLIENT_ID)
                        .requestServerAuthCode(GOOGLE_CLIENT_ID)
                        .requestScopes(new Scope("profile"))
                        .build();

        // Build a GoogleApiClient with access to GoogleSignIn.API and the options above.
                mGoogleApiClient = new GoogleApiClient.Builder(this)
                        .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                            @Override
                            public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                                Log.d(TAG, "onConnectionFailed: ");
                            }
                        })
                        .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                        .build();
            }

     public void googleAdditionalDetailsResult(Intent data) {
            Log.d(TAG, "googleAdditionalDetailsResult: ");
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Signed in successfully
                GoogleSignInAccount acct = result.getSignInAccount();
                // execute AsyncTask to get data from Google People API
                new GoogleAdditionalDetailsTask().execute(acct);
            } else {
                Log.d(TAG, "googleAdditionalDetailsResult: fail");
                startHomeActivity();
            }
        }

    private void startGoogleAdditionalRequest() {
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            startActivityForResult(signInIntent, RC_SIGN_GOOGLE);
        }

异步任务以获取其他详细信息

public class GoogleAdditionalDetailsTask extends AsyncTask {
        @Override
        protected Person doInBackground(GoogleSignInAccount... googleSignInAccounts) {
            Person profile = null;
            try {
                HttpTransport httpTransport = new NetHttpTransport();
                JacksonFactory jsOnFactory= JacksonFactory.getDefaultInstance();

                //Redirect URL for web based applications.
                // Can be empty too.
                String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";

                // Exchange auth code for access token
                GoogleTokenResponse tokenRespOnse= new GoogleAuthorizationCodeTokenRequest(
                        httpTransport,
                        jsonFactory,
                        GOOGLE_CLIENT_ID,
                        GOOGLE_CLIENT_SECRET,
                        googleSignInAccounts[0].getServerAuthCode(),
                        redirectUrl
                ).execute();

                GoogleCredential credential = new GoogleCredential.Builder()
                        .setClientSecrets(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET)
                        .setTransport(httpTransport)
                        .setJsonFactory(jsonFactory)
                        .build();

                credential.setFromTokenResponse(tokenResponse);

                People peopleService = new People.Builder(httpTransport, jsonFactory, credential)
                        .setApplicationName(App.getInstance().getString(R.string.app_name))
                        .build();

                // Get the user's profile
                profile = peopleService.people().get("people/me").execute();
            } catch (IOException e) {
                Log.d(TAG, "doInBackground: " + e.getMessage());
                e.printStackTrace();
            }
            return profile;
        }

        @Override
        protected void onPostExecute(Person person) {
            if (person != null) {
                if (person.getGenders() != null && person.getGenders().size() > 0) {
                    profileGender = person.getGenders().get(0).getValue();
                }
                if (person.getBirthdays() != null && person.getBirthdays().get(0).size() > 0) {
//                    yyyy-MM-dd
                    Date dobDate = person.getBirthdays().get(0).getDate();
                    if (dobDate.getYear() != null) {
                        profileBirthday = dobDate.getYear() + "-" + dobDate.getMonth() + "-" + dobDate.getDay();
                        profileYearOfBirth = DateHelper.getYearFromGoogleDate(profileBirthday);
                    }
                }
                if (person.getBiographies() != null && person.getBiographies().size() > 0) {
                    profileAbout = person.getBiographies().get(0).getValue();
                }
                if (person.getCoverPhotos() != null && person.getCoverPhotos().size() > 0) {
                    profileCover = person.getCoverPhotos().get(0).getUrl();
                }
                Log.d(TAG, String.format("googleOnComplete: gender: %s, birthday: %s, about: %s, cover: %s", profileGender, profileBirthday, profileAbout, profileCover));
            }
            startHomeActivity();
        }
    }

改变你onActivityResult像这样:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_GOOGLE) {    // result for addition details request
            googleAdditionalDetailsResult(data);
            return;
        } else if (requestCode == RC_SIGN_IN && resultCode == RESULT_OK) {  //logged in with firebase
            if (FirebaseAuth.getInstance().getCurrentUser().getProviders().get(0).equals("google.com")) {
            // user logged in with google account using firebase ui
                startGoogleAdditionalRequest();
            } else {
            // user logged in with google
                startHomeActivity();
            }
        } else {
            // handle error
        }
    }

更新:如果代码出错

personFields掩码是必需的

然后使用以下代码:

profile = peopleService.people().get("people/me"). setRequestMaskIncludeField("person.names,person.emailAddress??es,person.genders,pe??rson.birthdays").exe??cute();

谢谢@AbrahamGharyali.


推荐阅读
  • Gitlab接入公司内部单点登录的安装和配置教程
    本文介绍了如何将公司内部的Gitlab系统接入单点登录服务,并提供了安装和配置的详细教程。通过使用oauth2协议,将原有的各子系统的独立登录统一迁移至单点登录。文章包括Gitlab的安装环境、版本号、编辑配置文件的步骤,并解决了在迁移过程中可能遇到的问题。 ... [详细]
  • oracle11.2.0.4的rac集群,其中一个节点出现故障,集群无法启动,使用crsctlcheckcrs查看集群状况如下:[grid@db2client]$crsctlche ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • 如何查询zone下的表的信息
    本文介绍了如何通过TcaplusDB知识库查询zone下的表的信息。包括请求地址、GET请求参数说明、返回参数说明等内容。通过curl方法发起请求,并提供了请求示例。 ... [详细]
  • 本文讨论了编写可保护的代码的重要性,包括提高代码的可读性、可调试性和直观性。同时介绍了优化代码的方法,如代码格式化、解释函数和提炼函数等。还提到了一些常见的坏代码味道,如不规范的命名、重复代码、过长的函数和参数列表等。最后,介绍了如何处理数据泥团和进行函数重构,以提高代码质量和可维护性。 ... [详细]
  • centos安装Mysql的方法及步骤详解
    本文介绍了centos安装Mysql的两种方式:rpm方式和绿色方式安装,详细介绍了安装所需的软件包以及安装过程中的注意事项,包括检查是否安装成功的方法。通过本文,读者可以了解到在centos系统上如何正确安装Mysql。 ... [详细]
  • 我尝试使用Vue.js在Laravel中实现imageupload吗?但是,我不知道为什么图像 ... [详细]
  • mysql自动打开文件_让docker中的mysql启动时自动执行sql文件
    本文提要本文目的不仅仅是创建一个MySQL的镜像,而是在其基础上再实现启动过程中自动导入数据及数据库用户的权限设置,并且在新创建出来的容器里自动启动My ... [详细]
  • 本文介绍了Redis的基础数据结构string的应用场景,并以面试的形式进行问答讲解,帮助读者更好地理解和应用Redis。同时,描述了一位面试者的心理状态和面试官的行为。 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • 微软评估和规划(MAP)的工具包介绍及应用实验手册
    本文介绍了微软评估和规划(MAP)的工具包,该工具包是一个无代理工具,旨在简化和精简通过网络范围内的自动发现和评估IT基础设施在多个方案规划进程。工具包支持库存和使用用于SQL Server和Windows Server迁移评估,以及评估服务器的信息最广泛使用微软的技术。此外,工具包还提供了服务器虚拟化方案,以帮助识别未被充分利用的资源和硬件需要成功巩固服务器使用微软的Hyper - V技术规格。 ... [详细]
  • 有意向可以发简历到邮箱内推.简历直达组内Leader.能做同事的话,内推奖励全给你. ... [详细]
  • 1.webkit内核中的一些私有的meta标签,这些meta标签在开发webapp时起到非常重要的作用(1) ... [详细]
  • IhaveaFirebasedatabasethatismodeledassuch:我有一个这样建模的Firebase数据库::users:some-random ... [详细]
author-avatar
烟为你吸_811
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有