How to add GitHub Login button to your Android app using Kotlin

How to add GitHub Login button to your Android app using Kotlin

Today, I’ll show you how to implement the ‘Log in with GitHub’ button into your Android app.

We’re going to use 3-legged Authorization(OAuth) to get the authorization code and exchange it later for the access token. Using the access token, we’ll be able to get user’s information and email address making an HTTP request to https://api.github.com/user

Lets get started!

First, we need to create the Client ID and Client Secret on the GitHub website.

Go to https://github.com/settings/developers and press the Register a new application button.

Fill the required fields and press Register application.

On the new page, you’ll see the Client ID and Client Secret we going to use later.

Creating the GitHub Login Button

First, add a Button to your XML file. In this example, we have a button in the middle of the activity_main.xml.

Create a new Kotlin object file by right-clicking on your app’s package name on the left side and go New > Kotlin File/Class.

Give it the name GithubConstants, choose Object and press OK.

Inside the new file, copy and paste the following code and replace the CLIENT_ID, CLIENT_SECRET and REDIRECT_URI with yours.

In your AndroidManifest.xml file, add internet permission.


In your Kotlin class of your Activity (In this example is the MainActivity), add a listener to your button, and create a Dialog with a WebView inside.

This WebView uses a custom WebViewClient, named GithubWebViewClient.

This helps to ‘catch’ the URL with the authorization code after the user has given access to your app.

After getting the authorization code, you need to exchange it for an access token by making an HTTP POST request to https://github.com/login/oauth/access_token

After having the access token, you can get user’s Id, Display Name, Profile pic URL and email address with an HTTP GET request.

Done!

You can find the final project here

If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!

Leave a Reply

avatar
  Subscribe  
Notify of

Follow me

Newsletter

Subcribe for weekly emails! Get my posts of the week right in your inbox!