Showing posts with label google-signin. Show all posts
Showing posts with label google-signin. Show all posts

Friday, August 10, 2018

Retrieving Users Gender While Google SignIn using Firebase but not getting all users Gender?

Leave a Comment

Scenario:

I am trying to login with GOOGLE SIGN IN using Firebase Google Login in my android app, my basic need is that to retrieve USER gender while USER sign in my app.

Problem:

Even if I am getting gender of USERS but NOT All USERS, so where is the problem because getting only some users gender is quite strange, so my question is that why i am not getting all users gender while login?

public void performFirebaseLogin(GoogleSignInAccount acct, final Context context, final LoginSPrefRepositoryImpl loginSPrefRepositoryImpl) {         AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);         final GoogleAccountCredential googleCredential = GoogleAccountCredential.usingOAuth2(                     context, Collections.singleton(Scopes.PROFILE));         mAuth.signInWithCredential(credential)                 .addOnCompleteListener((Activity) context, new OnCompleteListener<AuthResult>() {                     @Override                     public void onComplete(@NonNull Task<AuthResult> task) {                         if (task.isSuccessful()) {                              FirebaseUser user = mAuth.getCurrentUser();                             if (user != null) {                             //here i am calling profile detail of user                                 new GetProfileDetails(user, googleCredential,loginSPrefRepositoryImpl).execute();                             } else {                                     onLoginListener.onFailure("Login Failed");                             }                         } else {                             // If sign in fails, display a message to the user.                             Log.w(TAG, "signInWithCredential:failure", task.getException());                         }                     }                 });     }   //here i am retrieving user's information    class GetProfileDetails extends AsyncTask<Void, Void, Person> {          private PeopleService ps;         private int authError = -1;         private FirebaseUser user;         private LoginSPrefRepositoryImpl loginSPrefRepositoryImpl;          GetProfileDetails(FirebaseUser user, GoogleAccountCredential credential, LoginSPrefRepositoryImpl loginSPrefRepositoryImpl) {              this.loginSPrefRepositoryImpl = loginSPrefRepositoryImpl;             this.user = user;             credential.setSelectedAccount(                     new Account(user.getEmail(), "com.google"));              HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();             JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();              ps = new PeopleService.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)                     .setApplicationName("Google Sign In Quickstart")                     .build();         }          @Override         protected Person doInBackground(Void... params) {             Person meProfile = null;             try {                 meProfile = ps                         .people()                         .get("people/me")                         .setPersonFields("genders")                         .execute();             } catch (UserRecoverableAuthIOException e) {                 e.printStackTrace();                 authError = 0;             } catch (GoogleJsonResponseException e) {                 e.printStackTrace();                 authError = 1;             } catch (IOException e) {                 e.printStackTrace();                 authError = 2;             }             return meProfile;         }          @Override         protected void onPostExecute(Person meProfile) {             //mainAct.printBasic();             if (authError == 0) { //app has been revoke, re-authenticated required.                 //mainAct.reqPerm();             } else if (authError == 1) {                 Log.w(TAG, "People API might not enable at" +                         " https://console.developers.google.com/apis/library/people.googleapis.com/?project=<project name>");             } else if (authError == 2) {                 Log.w(TAG, "API io error");             } else {                 if (meProfile != null) {                     // Log.d("kkkk", "" + meProfile.getGenders());                     JSONArray jsonArray = new JSONArray(meProfile.getGenders());                     try {                         JSONObject jsonObject = jsonArray.getJSONObject(0);                         String gender = jsonObject.getString("formattedValue");                         loginSPrefRepositoryImpl.isLoggedIn();                         loginSPrefRepositoryImpl.setGender(gender);                         onLoginListener.onSuccess(user);                     } catch (JSONException e) {                         e.printStackTrace();                         onLoginListener.onFailure("Something went wrong !");                     }                 }             }         }     } 

1 Answers

Answers 1

The thing is that gender should be explicitly shared by the user on his Google + account. I suggest you to experiment by yourself.

  1. Go to this page https://developers.google.com/people/api/rest/v1/people/get
  2. Type resourceName = people/me and personFields = genders
  3. Do the request, most likely you'll get the response with only resourceName and etag fields.
  4. Now go to https://plus.google.com/u/0/me page, which will open your G+ page and open Account Settings. Or you can open https://aboutme.google.com/u/0/ page directly.
  5. Click on the icon next to your Gender. This is the visibility setting, so user can choose if he wants to make his gender public, private or share only with circles. I suggest you to try different visibility options and check how it changes response at the step #3.

TL;DR: There is Gender visibility setting on G+, user may have chosen not to share his gender and there is no dedicated profile scope to request during auth for it. This setting is competely private.

Read More

Wednesday, January 10, 2018

Retrieving list of people who use the same requesting application using Google Sigin SDK

Leave a Comment

When a user sign-in using Google sign-in SDK is there any way to retrieve the users friends list who are already authenticated / sing-in to my app ? I did not find anything related to this in new Google People API. The old Google+ API has this. am I missing something ?

Thanks

0 Answers

Read More

Wednesday, February 8, 2017

Server-side Google Sign-In, way to encrypt/decrypt data with Google-managed secrets?

Leave a Comment

It's rather straightforward to use the Google Sign-In library on the server side and attain a GoogleIdToken to validate a user's identity. However, I'd like to encrypt per-user data in my database with a secret that's unique to every user. Is there an easy way to do this? If not using Google Sign-in, you can derive keys from a user's password, but that's obviously not possible here.

3 Answers

Answers 1

Well, first of all, you're drawing a parallel to using the user's password to derive an encryption key, but since you're talking about that as an alternative if you weren't using Google Sign-On, that implies your talking about using the password that users would authenticate with. That's a bad idea.

Users need to be able to change their authentication password, and that will be a major hassle for you if you're encrypting with it. It will require you to decrypt everything with the old password and then re-encrypt it with the new one.

So what you need to find is something that you can pull out of the GoogleIdToken that will never change. Email addresses change, so I wouldn't use that. Perhaps the user id, which you can get with GoogleIdToken.getPayload().getSubject() is what you want. Then what you would want to do is derive a key from that. I would look for ways to combine it with other information that the user gives you that really is secret, though.

Answers 2

I really don't know anything about this, so I'm kinda just thinking out loud.

To get some idea as to the general process for using Google Sign In I've been looking over the following guides found at the Google Sign-in for Websites page

  • Integrate Google Sign-In
  • Authenticate with a Backend Server
  • Google Sign-In for Server-Side Apps

Anyway, it seemes like it should be possible to use some combination of immutable characteristics of the users GoogleIdToken like their email, user id, etc in combination with some immutable characteristics of your app or web site, such as the app id or some other secret and create a hash value from that. Use that as your encryption key, or maybe send that thru OpenSSH or something for a stronger encryption hash.

Seems like in interesting problem, wish I had some insight into solving it. Perhaps I will research this more as I have a few interesting side projects I'm tinkering on.

Answers 3

The information you receive during a Google sign on is intended for authentication purposes. The id token is encoded as a Json Web Token. There is nothing secret in a JWT.

The information is cryptographically signed by the authentication provider, so you can verify the information. This is of no help for deriving secrets, though.

Looks like you'll have to find another way.

Read More

Saturday, January 14, 2017

Google Sign in not working

Leave a Comment

I am following Google's documentation for Google Sign. Having a weird problem when I call

Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent (mGoogleApiClient);         startActivityForResult (signInIntent, RC_SIGN_IN); 

Its seems Intent has been fired but I can't see account picker dialog. I am using

compile "com.google.android.gms:play-services-auth:9.6.1"

When I check does googleclient object is connected, it returns true.

Implementation

@OnClick (R.id.google_singin_button) void signInButtonClicked () {      HashMap<String, Object> map = new HashMap<> ();     map.put (AllAnalytics.LABEL, AllAnalytics.Label.SIGN_IN_GOOGLE);     map.put (AllAnalytics.ACTION, AllAnalytics.Action.CLICK);     map.put (AllAnalytics.CATEGORY, AllAnalytics.Category.REGISTRATION_SCREEN);      aa.analyticsEventOccur (map);      if (null != mGoogleApiClient) {        // Log.e(TAG,mGoogleApiClient.isConnected()+"");         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(Activity.RESULT_CANCELED != resultCode)     if (requestCode == RC_SIGN_IN) {         GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent (data);         handleSignInResult (result);     } }  @Override public void onCreate (Bundle savedInstanceState) {     super.onCreate (savedInstanceState);     mActivity = (RegisterActivity) getActivity ();     GoogleSignInOptions gso             = new GoogleSignInOptions.Builder (GoogleSignInOptions.DEFAULT_SIGN_IN)             .requestServerAuthCode (getString (R.string.google_client_auth), false)             .requestEmail ()             .build ();      mGoogleApiClient = new GoogleApiClient.Builder (getContext ())             .enableAutoManage (mActivity , this)             .addApi (Auth.GOOGLE_SIGN_IN_API, gso)             .build ();  } 

Log Cat

Class not found when unmarshalling: com.google.android.gms.auth.api.signin.internal.SignInConfiguration java.lang.ClassNotFoundException: com.google.android.gms.auth.api.signin.internal.SignInConfiguration    at java.lang.Class.classForName(Native Method)    at java.lang.Class.forName(Class.java:309)    at java.lang.Class.forName(Class.java:273)    at android.os.Parcel.readParcelableCreator(Parcel.java:2281)    at android.os.Parcel.readParcelable(Parcel.java:2245)    at android.os.Parcel.readValue(Parcel.java:2152)    at android.os.Parcel.readArrayMapInternal(Parcel.java:2485)    at android.os.BaseBundle.unparcel(BaseBundle.java:221)    at android.os.BaseBundle.containsKey(BaseBundle.java:269)    at android.content.Intent.hasExtra(Intent.java:4884)    at com.miui.server.XSpaceManagerService.isPublicIntent(XSpaceManagerService.java:174)    at com.android.server.am.ActivityStackSupervisorInjector.checkXSpaceControl(ActivityStackSupervisorInjector.java:56)    at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:897)    at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:3478)    at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:3465)    at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:140)    at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2245)    at android.os.Binder.execTransact(Binder.java:446) Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.auth.api.signin.internal.SignInConfiguration" on path: DexPathList[[directory "."],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)    at java.lang.Class.classForName(Native Method)     at java.lang.Class.forName(Class.java:309)     at java.lang.Class.forName(Class.java:273)     at android.os.Parcel.readParcelableCreator(Parcel.java:2281)     at android.os.Parcel.readParcelable(Parcel.java:2245)     at android.os.Parcel.readValue(Parcel.java:2152)     at android.os.Parcel.readArrayMapInternal(Parcel.java:2485)     at android.os.BaseBundle.unparcel(BaseBundle.java:221)     at android.os.BaseBundle.containsKey(BaseBundle.java:269)     at android.content.Intent.hasExtra(Intent.java:4884)     at com.miui.server.XSpaceManagerService.isPublicIntent(XSpaceManagerService.java:174)     at com.android.server.am.ActivityStackSupervisorInjector.checkXSpaceControl(ActivityStackSupervisorInjector.java:56)     at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:897)     at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:3478)     at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:3465)     at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:140)     at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2245)     at android.os.Binder.execTransact(Binder.java:446)      Suppressed: java.lang.ClassNotFoundException: com.google.android.gms.auth.api.signin.internal.SignInConfiguration    at java.lang.Class.classForName(Native Method)    at java.lang.BootClassLoader.findClass(ClassLoader.java:781)    at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)    at java.lang.ClassLoader.loadClass(ClassLoader.java:504)         ... 19 more Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available  10-11 23:46:17.873 1387-4537/? E/JavaBinder: *** Uncaught remote exception!  (Exceptions are not yet supported across processes.) java.lang.RuntimeException: Parcel android.os.Parcel@33c1f490: Unmarshalling unknown type code 6684783 at offset 320    at android.os.Parcel.readValue(Parcel.java:2228)    at android.os.Parcel.readArrayMapInternal(Parcel.java:2485)    at android.os.BaseBundle.unparcel(BaseBundle.java:221)    at android.os.BaseBundle.containsKey(BaseBundle.java:269)    at android.content.Intent.hasExtra(Intent.java:4884)    at com.miui.server.XSpaceManagerService.shouldResolveAgain(XSpaceManagerService.java:145)    at com.android.server.am.ActivityStackSupervisorInjector.resolveXSpaceIntent(ActivityStackSupervisorInjector.java:68)    at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:898)    at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:3478)    at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:3465)    at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:140)    at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2245)    at android.os.Binder.execTransact(Binder.java:446)   10-11 23:46:17.873 1387-4537/? A/ActivityManager: Activity Manager Crash java.lang.RuntimeException: Parcel android.os.Parcel@33c1f490: Unmarshalling unknown type code 6684783 at offset 320     at android.os.Parcel.readValue(Parcel.java:2228)     at android.os.Parcel.readArrayMapInternal(Parcel.java:2485)     at android.os.BaseBundle.unparcel(BaseBundle.java:221)     at android.os.BaseBundle.containsKey(BaseBundle.java:269)     at android.content.Intent.hasExtra(Intent.java:4884)     at com.miui.server.XSpaceManagerService.shouldResolveAgain(XSpaceManagerService.java:145)     at com.android.server.am.ActivityStackSupervisorInjector.resolveXSpaceIntent(ActivityStackSupervisorInjector.java:68)     at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:898)     at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:3478)     at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:3465)     at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:140)     at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2245)             at android.os.Binder.execTransact(Binder.java:446) 

3 Answers

Answers 1

Try to implement GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener on your activity and try code below

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)             .requestEmail()             .build();     google_api_client = new GoogleApiClient.Builder(LoginActivity.this)             .addConnectionCallbacks(LoginActivity.this)             .addOnConnectionFailedListener(LoginActivity.this)             .addApi(Plus.API)             .addScope(Plus.SCOPE_PLUS_PROFILE)             .addScope(Plus.SCOPE_PLUS_LOGIN)             .build();     if (google_api_client.isConnected()) {         google_api_client.connect();     }   @Override protected void onStart() {     super.onStart();     google_api_client.connect(); }   @Override protected void onStop() {     super.onStop();     if (google_api_client.isConnected()) {         google_api_client.disconnect();     } }   @Override public void onConnected(@Nullable Bundle bundle) {     if (google_api_client.isConnected() && is_gglSignInBtn_clicked) {         google_api_client.clearDefaultAccountAndReconnect();      }     if (is_gglSignInBtn_clicked) {         getProfileInfo();         is_gglSignInBtn_clicked = false;     } }  @Override public void onConnectionSuspended(int i) {     google_api_client.connect(); }  private void gPlusSignIn() {     if (!google_api_client.isConnecting()) {         if (is_gglSignInBtn_clicked && google_api_client.isConnected()) {             google_api_client.clearDefaultAccountAndReconnect();             getProfileInfo();         } else {             resolveSignInError();         }      }  }  @Override public void onConnectionFailed(@NonNull ConnectionResult result) {     if (!result.hasResolution()) {         google_api_availability.getErrorDialog(this, result.getErrorCode(), request_code).show();         return;     }     if (!is_intent_inprogress) {          connection_result = result;           if (is_gglSignInBtn_clicked) {             resolveSignInError();         }     }  }  private void resolveSignInError() {     if (connection_result != null) {         if (connection_result.hasResolution()) {             try {                 is_intent_inprogress = true;                 connection_result.startResolutionForResult(this, SIGN_IN_CODE);             } catch (IntentSender.SendIntentException e) {                 is_intent_inprogress = false;                 google_api_client.connect();             }         }     } }  private void getProfileInfo() {     try {         mProgressDialog.setMessage("Signing in....");         mProgressDialog.show();         if (Plus.PeopleApi.getCurrentPerson(google_api_client) != null) {             Person currentPerson = Plus.PeopleApi.getCurrentPerson(google_api_client);              Log.i("googleEmail", "" + (Plus.AccountApi.getAccountName(google_api_client)));             email = "" + (Plus.AccountApi.getAccountName(google_api_client));             setPersonalInfo(currentPerson);         } else {             Toast.makeText(getApplicationContext(),                     "No Personal info mention", Toast.LENGTH_LONG).show();             finish();         }      } catch (Exception e) {         e.printStackTrace();     }  }  private void setPersonalInfo(Person currentPerson) {      try {         JSONObject googleJsonObject = new JSONObject(currentPerson + "");         familyName = googleJsonObject.getJSONObject("name").optString("familyName");         givenName = googleJsonObject.getJSONObject("name").optString("givenName");         gender = googleJsonObject.optString("gender");         displayName = googleJsonObject.optString("displayName");         googleId = googleJsonObject.optString("id");         imageUrl = "http://res.cloudinary.com/demo/image/gplus/" + googleId + ".jpg";      } catch (JSONException e) {         e.printStackTrace();     } 

Answers 2

Just check your onActivityResult() is called or not because you have used Fragment. So you have to pass the Activity result from activity to fragment.

In your RegisterActivity you have to write this

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {     Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);     fragment.onActivityResult(requestCode, resultCode, data); } 

and then you will receive result in your Fragment.

Hope it helps you.

Answers 3

Have you tried disabling ProGuard? Set minifyEnabled to false in your build.gradle and see if it helps, your configuration may be out of date or incorrect.

Also you can check if your device is runing 9.6.1+ version of Google Play services.

Read More

Sunday, April 3, 2016

WebApi2 Google OAuth2 middleware error response

Leave a Comment

For user authentication with external providers such as Google, it is using specific Owin middlewares. As for example Microsoft.Owin.Security.Google. WebAPI2 template uses this to support implicit flow authentication (response_type=token). But what about Code flow?

Is it possible to implement Code flow (response_type=code)?

After debugging those OAuth providers I noticed that passing return_type=code to Google, it successfully authenticates and returns json with access and refresh tokens, then user gets signed in by api/Account/ExternalLogin endpoint but at the end of the flow I get redirected to http://localhost:50321/?error=unsupported_response_type#.

I could not really find the flow where and why it is setting this specific error in the assembly.

Startup.Auth.cs looks like this:

public void ConfigureAuth(IAppBuilder app)     {         app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);          PublicClientId = "self";         var tokenTimeSpanInHours = ConfigurationManager.AppSettings["AccessTokenLifeTimeInHours"];          OAuthServerOptions = new OAuthAuthorizationServerOptions         {             Provider = new ApplicationOAuthProvider(PublicClientId),             TokenEndpointPath = new PathString("/api/token"),             AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),             AccessTokenExpireTimeSpan = TimeSpan.FromHours(Convert.ToInt16(tokenTimeSpanInHours)),             AllowInsecureHttp = true         };          app.UseOAuthBearerTokens(OAuthServerOptions);         var googleOAuthOptions = new GoogleOAuth2AuthenticationOptions         {             AccessType = "offline",             Provider = new CustomGoogleAuthProvider(),             ClientId = ConfigurationManager.AppSettings["GoogleAccountClientId"].ToString(),             ClientSecret = ConfigurationManager.AppSettings["GoogleAccountClientSecret"].ToString()                    };         googleOAuthOptions.Scope.Add("profile");         googleOAuthOptions.Scope.Add("email");         googleOAuthOptions.Scope.Add("https://www.googleapis.com/auth/gmail.send");         app.UseGoogleAuthentication(googleOAuthOptions);     } 

Where is the problem then? Do I need some explicit configuration to tell that I want code flow? Is it supported?

0 Answers

Read More