我正在尝试使用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
,但它只包括idpSecret
和idpToken
.如何访问性别和生日等个人资料的其他请求字段?我可以访问公共领域的电子邮件,姓名,照片等
FirebaseAuth.getInstance().getCurrentUser();
Sabeeh.. 8
Firebase不支持,但您可以通过以下方式执行此操作:
首先,您需要client_id和client_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.
Firebase不支持,但您可以通过以下方式执行此操作:
首先,您需要client_id和client_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.