This guide describes the process of configuring your Backendless backend to enable the Google account sign-in in your application.

 

Adding Google+ API and generating client ID

1.Open https://console.developers.google.com in a browser.
2.Choose an existing project or create a new one.
newproject-google-signin
3.Select the Google+ API:
select-google-plus
4.Click Enable to enable the API:
click-to-enable
5.Once the API is enabled, click the Go to credentials button:
goto-credentials
6.Select Android in the Where will you be calling the API from? drop-down list.
Also select User data in the What data will you be accessing? section as shown below:
credentials
7.Click the What credentials do I need? button.

 

8.Copy the command starting with keytool... using the copy icon:
copy-keytool-command
9.Open a command prompt/terminal window. Run the keytool command, but make sure to set the value for the -keystore argument. The value must be the proper path to the debug or the production keystore. For example, for the Android apps, the default location of the keystore is ~/.android/debug.keystore, the default password is android.
10.The output of the keytool command includes the SHA-1 certificate fingerprint. Copy its value and paste into the field on the Add credentials to your project screen located right below the keytool command box:
copy-sha1
11.Enter the package name which you will use in your application and click Create client ID.
12.Once the client ID is generated, enter the name of the product on the final screen and click Continue.
product-name
13.Click Done on the final screen.

 

Generating config file for client project

1.Navigate to https://developers.google.com/mobile/add
2.Click the Pick a platform button and make a platform (Android or iOS) selection.
3.Select the app from the dropdown, enter package name (Android) or bundle ID (iOS).
4.Click Choose and configure services.
5.Click Google Sign-in, then click Enable Google Sign-In.
6.Click Continue to Generate configuration files.
7.Click Download google-services.json.

 

Configuring Backend

1.Return to https://console.developers.google.com
2.Select the project and click Credentials.
3.The credentials should now include a "Web client" which is automatically generated by Google.
webclient
4.Click Web client.
5.Copy Client ID and Client secret into Google Plus ID and Google Plus Secret located in the Manage > App Settings > Social Settings in Backendless console:
client-id
 
social-settings
6.Click Save buttons in Backendless console.

 

Developing Client App

1.Add google-services.json generated in the Generating config file for the client project section to the root of the "app" module in the Android project.
2.Add the following code in the onCreate method.
@Override
  public void onCreate( Bundle savedInstanceState )
  {
    super.onCreate( savedInstanceState );

    FragmentActivity fragmentActivity = (FragmentActivity)this.getActivity();

    gSignInOptions = new GoogleSignInOptions.Builder( GoogleSignInOptions.DEFAULT_SIGN_IN )
            .requestEmail().requestProfile().requestId().requestIdToken( SERVER_CLIENT_ID )
            .build();

    // Build a GoogleApiClient with access to GoogleSignIn.API and the options above.
    GoogleApiClient.Builder apiCliBuilder = new GoogleApiClient.Builder( fragmentActivity );
    gApiClient = apiCliBuilder
            .enableAutoManage( fragmentActivity, this )
            .addApi( Auth.GOOGLE_SIGN_IN_API, gSignInOptions ).build();
  }

3.The SERVER_CLIENT_ID variable in the code above must be the value of the Web Client ID from the Credentials screen:
web-client-id
4.To start the sign in process, use the following code, where SIGN_IN_INTENT_ID is an integer identifying the intent (it will be used later in the code):
public int SIGN_IN_INTENT_ID = 1;
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent( gApiClient );
this.startActivityForResult( signInIntent, SIGN_IN_INTENT_ID );
5.The intent displays a screen where the user selects her account and optionally enters the credentials. Once the activity result is available, it is delivered to the following method. The implementation of the method further delegates the sign in process:
@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 == SIGN_IN_INTENT_ID) 
    {
      GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

      if (result.isSuccess()) 
      {
        refreshUIonLogin( this.getActivity(), result.getSignInAccount() );
        loginInBackendless( result.getSignInAccount() );
      } 
      else
      {
        logined = false;
        refreshUIonLogout();
        // Signed out, show unauthenticated UI.
      }
    }
  }

  private void loginInBackendless(final GoogleSignInAccount acct)
  {
    Log.d( TAG, "handleSignInResult: try login to backendless" );

    final MainActivity mainActivity = (MainActivity)this.getActivity();
    final String accountName = acct.getEmail();
    final String scopes = "oauth2:" + Scopes.PLUS_LOGIN + " " + 
                          Scopes.PLUS_ME + " " + Scopes.PROFILE + " " + 
                          Scopes.EMAIL;

    AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>(){
      @Override
      protected String doInBackground( Void... params )
      {
        String token = null;
        try
        {
          token = GoogleAuthUtil.getToken( mainActivity, accountName, scopes );
          GoogleAuthUtil.invalidateToken( mainActivity, token );
          handleAccessTokenInBackendless( acct.getIdToken(), token );
        }
        catch( UserRecoverableAuthException e )
        {
          startActivityForResult( e.getIntent(), REQUEST_AUTHORIZATION );
        }
        catch( Exception e )
        {
          Log.e( TAG, e );
        }
        return token;
      }
    };

    task.execute( );
  }



private void handleAccessTokenInBackendless( String idToken, String accessToken )
  {
    Log.d( TAG, "idToken: "+idToken+ ", accessToken: "+accessToken );

    Map<String, String> googlePlusFieldsMapping = new HashMap<String, String>();
    googlePlusFieldsMapping.put( "given_name", "gp_given_name" );
    googlePlusFieldsMapping.put( "family_name", "gp_family_name" );
    googlePlusFieldsMapping.put( "gender", "gender" );
    googlePlusFieldsMapping.put("email", "email");
    List<String> permissions = new ArrayList<String>();

    if (idToken != null && accessToken != null)
    Backendless.UserService.loginWithGooglePlusSdk( idToken, 
                                                    accessToken, 
                                                    googlePlusFieldsMapping, 
                                                    permissions, 
                                                    new AsyncCallback<BackendlessUser>()
    {
      @Override
      public void handleResponse( BackendlessUser backendlessUser )
      {
        Log.i( TAG, "Logged in to backendless, user id is: " + backendlessUser.getObjectId() );
        refreshUIonLoginBackendless(LoginFragment.this.getActivity(), backendlessUser );
      }

      @Override
      public void handleFault( BackendlessFault backendlessFault )
      {
        Log.e( TAG, "Could not login to backendless: " + 
                    backendlessFault.getMessage() + 
                    " code: " + backendlessFault.getCode() );
      }
    });
  }

 


Please let us know how we can improve the documentation by leaving a comment. All technical questions should be posted to the Backendless Support forum. We do not respond to the technical questions on the documentation pages.: