how to retrieve email from gplus using android - android

I am trying to find the latest solution with GoogleApiClient.Plus.API (android) for getting the email for the gplus profile. In internet, stackoverflow, every example found is obsolete and deprecated and of no use.
If it can be fetched only from Auth.GOOGLE_SIGN_IN_API then is it a two step process to fetch half of info from Auth API and rest from Plus.API ??
Thanks in advance for answer.

First I assume you have a button for google plus sign in
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
break;
}
}
At your onActivityResult you will catch sign in result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from and you can extract your user information there
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
//This line is your need
String yourEmail = acct.getEmail();
}
}
}

Here is how to get the email that is associated with the device, and probably with your app too:
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(context).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) { //If email matches the account associated with the device
String possibleEmail = account.name;
...
}
}
Let me know if this worked

After two days of struggle at last this post saved my life ..
How to get profile like gender from google signin in Android?
But the apis are obsolete, did a bit of scratch head and could make it work.
create your google api client like this
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestScopes(new Scope(Scopes.PLUS_LOGIN))
.build();
m_GoogleApiClient = new GoogleApiClient.Builder(m_activity)
.enableAutoManage(m_activity, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addApi(Plus.API)
.build();
then on onActivityResult()
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
GoogleSignInAccount acct = result.getSignInAccount();
fetchConnectedProfileInfo();
}
public void fetchConnectedProfileInfo()
{
Log.d(TAG, "fetchConnectedProfileInfo");
if (m_GoogleApiClient.hasConnectedApi(Plus.API)) {
Plus.PeopleApi.load(m_GoogleApiClient, "me").setResultCallback(this);
}
}
Refer my github page for full code sample https://github.com/sandipsahoo2k2/social-login

Related

GoogleSignIn.getLastSignedInAccount() returns null on release build

I'm trying to add google sign-in to my android app. Everything works fine on debug build. But when I push the apk for internal testing on Google Play it throws Google SignIn API Exception 10. Should I add anything extra to my console?
So far I've done the following things,
Created new firebase project
Added SHA-1 to firebase console.
Downloaded google-services.json from firebase and copied to app
folder.
On my https://console.cloud.google.com/apis/credentials
page everything is automatically filled by firebase. So, I didn’t do
anything there.
Add all required libraries to android project
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
SignInButton signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, so);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
// Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
Log.e(TAG, "firebaseAuthWithGoogle:" + account.getId());
//firebaseAuthWithGoogle(account.getIdToken());
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.e(TAG, "Google sign in failed", e);
}
handleSignInResult(task);
}
}
HandleSignInResult;
private void handleSignInResult(Task<GoogleSignInAccount>
completedTask) {
String personName = "", personEmail = "", aid = "";
Uri personPhoto = Uri.parse("");
// GoogleSignInAccount acct =
GoogleSignIn.getLastSignedInAccount(this);
GoogleSignInAccount acct = completedTask.getResult();
if (acct != null) {
personName = acct.getDisplayName();
personEmail = acct.getEmail();
personPhoto = acct.getPhotoUrl();
aid = acct.getId();
Log.e("ID_TOKEN", acct.getIdToken() + "");
}
}
It's now working after I added the SHA-1 from Google Play console under Release -> Setup -> App integrity as #lasagnakid77 mentioned in his comment.

Firebase Google Login Failed

I am using firebase Google Sign In. It was working fine until i upload my app to the play store. I am getting Sign In Failed Problem. Another problem that i am facing with when a user successfully signs in it returns :
bad getToken() -> BAD_AUTHENTICATION. Account.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
assert account != null;
firebaseAuthWithGoogle(account);
} else {
// check internet connection, display a message to the user.
Toast.makeText(LRActivity.this, "Signin Failed", Toast.LENGTH_SHORT).show();
}
}
}
Here is the token request :
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.requestScopes(new Scope("https://www.googleapis.com/auth/youtube")) // you can request scope here OR at the time of subscribe
.build();
You can follow this link to get a SHA from play store console and update it on your firebase console.
And then you don't need to update a new apk on your console.
There will be 3 SHA1 on your firebase console :
Debug SHA1.
Release SHA1.
Play Store Console SHA1.

Google Sign in not working properly

I have integrated sign in with google in my android application, now issue is that in some device its not working,but in my emulator and in some device it is working fine,what is the issue?
https://developers.google.com/identity/sign-in/android/
http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/
this two tutorials to sign in, but when i run my app, and try to login it allows to select account,but when i click on that in my logcat it shows
System.out: Google logout
CODE
private void handleSignInResult(GoogleSignInResult result) {
Log.d("", "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
Log.e("", "display name: " + acct.getDisplayName());
personName = acct.getDisplayName();
personPhotoUrl = String.valueOf(acct.getPhotoUrl());
ggoleemail = acct.getEmail();
googleid = "G" + acct.getId();
// String baday = String.valueOf(acct.getAccount());
Log.e(TAG, "Name: " + personName + googleid + ", email: " + ggoleemail
+ ", Image: " + personPhotoUrl);
/* txtName.setText(personName);
txtEmail.setText(email);
Glide.with(getApplicationContext()).load(personPhotoUrl)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgProfilePic);
*/
googleslogins();
// updateUI(true);
} else {
// Signed out, show unauthenticated UI.
//updateUI(false);
System.out.println("Google logout");
}
}
Have you added your certificate's hash on Google developer console and turned on the APIs in the Google API manager?
APIs - GooglePlus and People Api
Follow this steps:
1. Generate SHA1 :
windows:
keytool -list -v -keystore "%USERPROFILE%.android\debug.keystore"
-alias androiddebugkey -storepass android -keypass android
Mac and Linux:
keytool -list -v -keystore ~/.android/debug.keystore -alias
androiddebugkey -storepass android -keypass android
2. Add your project on google console. Add certification by entering SHA1.
3. Enable google sigin from firebase console. Download json file.
4. Add this code to android:
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result)
{
Log.d("TAG", "handleSignInResult:" + result.isSuccess());
if (result.isSuccess())
{
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
String email = acct.getEmail();
String name = acct.getDisplayName();
Uri phone = acct.getPhotoUrl();
String photo = String.valueOf(phone);
String[] user_name = name.split("\\s+");
String fname = user_name[0];
String lname =user_name[1];
Log.d("email", email);
Log.d("photo", photo);
Log.d("u_name", name);
Log.d("f_name", fname);
Log.d("l_name", lname);
}
}
First at most, need to check whether google play services version in correctly installed
public static boolean checkPlayServices(Activity context) {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(context);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
//apiAvailability.getErrorDialog(context, resultCode, 9000).show();
} else {
//show error message
}
return false;
}
return true;
}
Make sure you have the correct google token. Make sure you enable Google + Sign in in google console
private void setupGoogle() {
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.google_token))
.requestScopes(new Scope(Scopes.PLUS_ME))
.requestEmail()
.requestProfile()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.enableAutoManage(getActivity(), this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addOnConnectionFailedListener(this)
.build();
}
Trigger Sign in
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, Constant.GG_SIGN_IN);
onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Constant.GG_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
firebaseAuthWithGoogle(result.getSignInAccount());
Logger.debug(new Gson().toJson(result.getSignInAccount()));
Logger.debug(new Gson().toJson(result.getStatus()));
//code here
}
else{
Logger.shortToast("google sign-in failed");
}
}
}
Based from this thread, you're getting an error maybe because the user's account is attached to both a hosted account and a Google account, and probably it has different passwords for each The authentication servers currently do not handle this well. Follow this Connecting to Google Drive with Google APIs Client Library for Java tutorial.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
// Google Accounts using OAuth2
m_credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(DriveScopes.DRIVE));
m_client = new com.google.api.services.drive.Drive.Builder(
m_transport, m_jsonFactory, m_credential).setApplicationName("AppName/1.0")
.build();
...
}
You can also check on these related issues:
Bad Authentication Error Rails connecting to google drive
Google Drive: 403 Authentication failed
Hope this helps!
There are a few things you are not doing. Firstly, you are losing a lot of information about why the connection is not successful because you are no inspecting the cause of the connection failure coming in the GoogleSignInResult parameter...
private void handleSignInResult(GoogleSignInResult result) {
}
Reading status codes
That parameter has useful information you are ignoring. You can retrieve the error status code if the sign-in is not successful...
private void handleSignInResult(GoogleSignInResult result) {
if(!result.isSuccess()){
Status status = result.getStatus();
}
}
With that status, you can check why the sign-in failed by checking the status code
int code = status.getStatusCode();
if(code == GoogleSignInStatusCodes.SIGN_IN_REQUIRED){
}
else if(code == GoogleSignInStatusCodes.NETWORK_ERROR){
}
All the constants can be found in the GoogleSignInStatusCode documentation here...
https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInStatusCodes
and here...
https://developers.google.com/android/reference/com/google/android/gms/common/api/CommonStatusCodes
Resolving the sign-in issue
You could even attempt to resolve the problem by tdetermining if the error has resolution...
private void handleSignInResult(GoogleSignInResult result) {
if(!result.isSuccess()){
Status status = result.getStatus();
if(status.hasResolution()){
status.startResolutionForActivity(this, SIGN_IN_RESOLUTION_REQUEST_CODE);
}
}
}
which will start an intent that could probably resolve the issue for the user. Then you can check the result of that resolution on the onActivityResult method...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == SIGN_IN_RESOLUTION_REQUEST_CODE){
}
}
Google API Availability
If all the above fails. The next thing you can do is check for Google API availability on the user's device.
Basically, in one comment you admitted that your solution is INDEED working in SOME devices.
If that is the case, then I'm inclined to point out that some Google Libraries require a specific version of Google Play services
The best way to know what exactly the problem is...it's by doing a Google API availability check and then output as much info as you can to logcat...you can do that easily, see below...
private boolean checkPlayServices(){
GoogleApiAvailability gaa = GoogleApiAvailability.getInstance();
int result = gaa.isGooglePlayServicesAvailable(getApplicationContext());
Log.d("isGooglePlayServicesAvailable returned %d", result);
if(result != ConnectionResult.SUCCESS){
if(gaa.isUserResolvableError(result)){
gaa.getErrorDialog(this,result, REQUEST_PLAY_SERVICES_RESOLUTION).show();
}
return false;
}
return true;
}
isGooglePlayServicesAvailable will return an integer constant that can be translated to one of the ConnectionResult constants. The list of constants and it's meaning is quite large to cover here.
Another key part of the code snippet above is that you could attempt to have the system resolve the error for you if the error is easily resolvable, for example, if the user needs to update Google Play Services on their device because the current version is outdated
Where would you use the above method?
Anywhere make the first connection attempt to Google APIs. For example, using your original code snippet...
private void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
//code block omitted
} else {
checkPlayServices();
}
}
Google Signup OR Social Signup.
After complete Code side must do other things from Google and Firebase Console.
Create SHA-1 Key from your pc.
- from Right side of Android studio find Gradle option -> app -> Signing Report. You will get SHA-1 key in log area when it done. (Watch in pic.)
- add this key in Google firebase Console in App module
- after this module, download ***'google-services.json'*** and paste it
into project -> app -> :here paste that file: ex:/ D:\Thor_PC\Androidroject\android-customer_new\app
- and at the last option must check **Google Service is Enable or not** in Console.
- Go to firebase console -> Engage (left side) -> Authentication -> Sign-in Method.
☻♥ Done Keep Code.

How to re-authenticate a user on Firebase with Google Provider?

The example for using reauthenticate() in Firebase shows only how to re-authenticate a user who signed with Email and Password:
AuthCredential credential = EmailAuthProvider.getCredential("user#example.com", "password1234");
FirebaseAuth.getInstance().getCurrentUser().reauthenticate(credential);
I also know how to re-authenticate with Facebook Provider (credential = FacebookAuthProvider.getCredential(AccessToken.getCurrentAccessToken().toString())).
Problem is there's no equivelant method in Google API to get the current Access Token and eventually get the AuthCredential. So what do I pass to getCredential() in this case?
I know this is old question but I did not found complete answer to this. This is how to do it on Android.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// Get the account
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(context);
if (acct != null) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
user.reauthenticate(credential).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Reauthenticated.");
}
}
});
}
Considering you would have received GoogleSignInResult as a response to sign-in, I think you can use the following code:
// assuming result variable has GoogleSignInResult
// GoogleSignInResult result
// Get the account
GoogleSignInAccount acct = result.getSignInAccount();
// credential
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
FirebaseAuth.getInstance().getCurrentUser().reauthenticate(credential).addOnCompleteListener(new OnCompleteListener<Void>() {...
You can get GoogleSignInResult via 2 way to authenticate.
i) By entering email id and password into google login screen.
ii) By selecting account from already logged in account in phone.
i have used 2nd approach to get access token and authenticate user.
for more support references links are given below.
google sign in link 1
Stackoverflow - token refresh
google auth provider documentation
server side token verification docs
if your only objective is, to get token so you can also try this github source.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
//use sign in option to build api client instence.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent,RC_SIGN_IN); }
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN){
GoogleSignInResult result =Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
} else {
// Signed out, show unauthenticated.
}
}
// get authenticated
AuthCredential credential =
GoogleAuthProvider.getCredential(acct.getIdToken(), null);
FirebaseAuth.getInstance().getCurrentUser().reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
// add your job here on authenticated
}
// if token is obsoleted then you can do this
credential.refreshToken();
accessToken = credential.getAccessToken();

Android get google token id

I have been following these two tutorials:
https://developers.google.com/identity/sign-in/android/sign-in
https://developers.google.com/identity/sign-in/android/backend-auth
I managed to integrate google login system into my android application but when I try to get token id I am get null.
When I try to use following code:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.build();
I get fail on user log in. When I call:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
I am unable to retrieve token.
I tried to merge this code to have:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken(getString(R.string.server_client_id))
.build();
but without any success.
Here is my code:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// [START onActivityResult]
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
// [END onActivityResult]
// [START handleSignInResult]
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName()));
updateUI(true);
String idToken = acct.getIdToken();
if (idToken != null) {
Log.d("TOKEN", idToken);
} else {
Log.d("TOKEN", "CHUUUUUUJ WIELKI!");
}
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
Google APIs use the OAuth 2.0 protocol for authentication and
authorization. Google supports common OAuth 2.0 scenarios such as
those for web server, installed, and client-side applications.
To begin, obtain OAuth 2.0 client credentials from the Google
Developers Console. Then your client application requests an access
token from the Google Authorization Server, extracts a token from the
response, and sends the token to the Google API that you want to
access. For an interactive demonstration of using OAuth 2.0 with
Google (including the option to use your own client credentials),
experiment with the OAuth 2.0 Playground.
For details Go Through requestIdToken returning null

Categories

Resources