Community Post

Android-Authentication with google

Hari Krishnan

Every developer needs their app to be as much user friendly as possible. The first thing to have such an approach is to provide a simpler registration process for the user in your app. So, here we are going to see how to implement google authentication in an android app. Let us go through the procedure. ​ ​

Getting a configuration file from Google

At first you need to get a configuration file from google for your application. To start with it, you should register your app here. After filling both the app name and package name fields here, click on "Choose and configure Services" button.

It will show a prompt to select which Google services you'd like to add to your app. Select the appropriate for your requirement. Now they will ask you to provide the SHA-1 hash value so that they can give you back an appropriate configuration file for your app.

Some of might be confused with what SHA-1 hash value is. It stands for "Secure Hash Algorithm 1". SHA-1 produces a 160-bit (20-byte) hash value which will help you for secure communication in your app. And dont worry, we are not here to go deep into that. We will make it simple and i will tell you how to find your SHA-1 hash value. But if you wanna know more about it then you can find it here.

Now we are gonna see how to find your SHA-1 hash value . You can get both debug mode hash value and release mode hash value. Use it appropriately.

To get debug mode SHA-1 hash value, use the command

keytool -exportcert -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore

​ ​ And to get the release SHA-1 hash value, use the command

keytool -exportcert -list -v \
-alias <your-key-name> -keystore <path-to-production-keystore>

​ ​ If you dont have a production keystore and you don't know what it is, Let me help here. A keystore file in android is something like a signature for authorizing your application. To generate this file the IDE (It might be Android Studio) will ask you to fill some fields like your name, company name and other such details. After filling all those details it will generate a keystore file for you. So you can select a path where your keystore file is to be saved and then give that path in the in the above command. ​ So, after providing the SHA-1 hash value to the google console, it will give you the google-service.json file. This is your configuration file. Copy it from your downloads folder and paste it inside your project/app folder. ​

Creating client ID

​ Google has a credential page for you to create your client ID. Each of your google app will have a client ID. Copy the client ID of app that you just created and place it in your res-> strings inside the project as"server_client_id" like below

<string name="server_client_id">YOUR_SERVER_CLIENT_ID</string>

Adding Google Services plugin

You can see two levels of graddle files inside your project. ​ -one is project level build graddle , add the below dependency at the end and plugin at the top inside your project level build graddle files.

apply plugin: 'com.google.gms.google-services'
classpath 'com.google.gms:google-services:2.0.0-alpha5'

​ -another is app level build graddle, add google play service below inside this graddle file.

compile 'com.google.android.gms:play-services-auth:8.4.0'

We have done with the first section to have google authentication. Now we will move towards the second phase.. ​

Getting information from google -

We need our activity to extend FragmentActivity and implement GoogleApiClient.OnConnectionFailedListener. ​ Inside the Activity we should have a GoogleApiClient declaired. and inside the onCreate method we should define the googleApiClent object and GoogleSignin options like below. ​

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
​
        // 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()
                .build();
​
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
​
        findViewById(R.id.sign_in_button).setOnClickListener(this);
    }

<com.google.android.gms.common.SignInButton
 android:id="@+id/sign_in_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:onClick="signIn">

Now when the user clicks on this button the signIn methode will be triggered, which is defined as below

 void signIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, "SOME_INTEGER");
}

The result will be in onActiviityResult from which you can get the user details.

 @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);
        GoogleSignInAccount acct = result.getSignInAccount();
          if (result.isSuccess()) {
            // Signed in successfully
​
            String personName = acct.getDisplayName();
            String personEmail = acct.getEmail();
            String personId = acct.getId();
​
            Log.e("name",personName);
            Log.e("Email",personEmail);
             Log.e("Id',personId);
​
        } else {
           //authentication failed
        }
    }
}

​ Done ! We now have the user information from google with us. You can even get the profile image url from the GoogleSignInAccount Object. ​

Conclusion

By this time, you will be able to integrate google authentication in your app. Happy coding !

Hari Krishnan

1 post

Exposure towards programming and enthusiastic in android development.