Authenticate Using GitHub on Android
GitHub is where over 65 million developers shape the future of software, together. Contribute to the open-source community, manage your Git repositories, review code like a pro, track bugs and features, power your CI/CD and DevOps workflows, and secure code before you commit it. So in this article, we are going to discuss how to authenticate using GitHub in your Android App with the help of Firebase User Authentication.
Steps for Firebase user Authentication using GitHub
Step 1:
Create a new project in android studio or open any existing project through with you want to authenticate a user by GitHub and add the firebase to that android application. Steps to add firebase in your application.
Step 2:
Go to your firebase console, go to your application then navigate to project settings and add fingerprint-like SHA1 of your connected application. To find SHA1 go to Gradle (right side of android-studio window ) > your-application-name > Tasks > Android > signingReport (double click on it)
Note: Make sure to add google-services.json in your application, otherwise, download it from the project settings of the firebase console and add it to your application.
Step 3:
Go back to your application in the firebase console, navigate to Authentication (left panel of firebase) then go to Sign-in-method enable GitHub provider.

Enable GitHub

Require Client ID & Client secret
Now, we need Client ID and Client Secret. For this register your app as a developer application on GitHub and get your app’s OAuth 2.0 Client ID and Client Secret. To register your app, write the application name, enter the app’s website homepage URL (here I’m giving the same URL as in the Authorization callback URL), and provide the application description in brief.

Register an app on GitHub
Note: Make sure your Firebase OAuth redirect URI (e.g. my-app-12345.firebaseapp.com/__/auth/handler) is set as your Authorization callback URL in your app’s settings page on your GitHub app’s config.
Get your authorizable callback URL as shown in the image below.

Get your authorization callback URL
Click Register application. You will get your Client ID and Client secret, copy and paste them in the firebase console (under sign-in-method) and click the save button to enable GitHub.
Step 4:
Come back to android studio. Add dependency for the Firebase Authentication Android library in your build.gradle (Module: your-application-name.app) by using the Firebase Android BoM .
dependencies {
// Import the BoM for the Firebase platform
implementation platform(‘com.google.firebase:firebase-bom:28.0.1’)
// Declare the dependency for the Firebase Authentication library
// When using the BoM, you don’t specify versions in Firebase library dependencies
implementation ‘com.google.firebase:firebase-auth-ktx’
}
By using the Firebase Android BoM, your app will always use compatible versions of the Firebase Android libraries.
Step 5: Working with the MainActivity file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < androidx.constraintlayout.widget.ConstraintLayout android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" > < LinearLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_margin = "10dp" android:orientation = "vertical" app:layout_constraintBottom_toBottomOf = "parent" app:layout_constraintEnd_toEndOf = "parent" app:layout_constraintStart_toStartOf = "parent" app:layout_constraintTop_toTopOf = "parent" > < EditText android:id = "@+id/githubId" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_marginTop = "100dp" android:hint = "Enter your email associated with github" android:padding = "8dp" android:textAlignment = "center" android:textColor = "#118016" /> < Button android:id = "@+id/github_login_btn" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_marginStart = "100dp" android:layout_marginTop = "10dp" android:layout_marginEnd = "100dp" android:layout_marginBottom = "100dp" android:backgroundTint = "#fff" android:drawableLeft = "@drawable/github" android:drawablePadding = "8dp" android:padding = "8dp" android:text = "@string/log_in_with_github" android:textAllCaps = "false" android:textColor = "#000" /> </ LinearLayout > </ androidx.constraintlayout.widget.ConstraintLayout > |
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.tasks.OnFailureListener import com.google.android.gms.tasks.OnSuccessListener import com.google.android.gms.tasks.Task import com.google.firebase.auth.AuthResult import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.OAuthProvider class MainActivity : AppCompatActivity() { private lateinit var firebaseUser: FirebaseUser private lateinit var loginBtn: Button private lateinit var githubEdit: EditText // firebaseAuth variable to be initialized later private lateinit var auth: FirebaseAuth // an instance of an OAuthProvider using its Builder // with the provider ID github.com private val provider = OAuthProvider.newBuilder( "github.com" ) override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) loginBtn = findViewById(R.id.github_login_btn) githubEdit = findViewById(R.id.githubId) // initializing auth auth = FirebaseAuth.getInstance() // Target specific email with login hint. provider.addCustomParameter( "login" , githubEdit.text.toString()) // Request read access to a user's email addresses. // This must be preconfigured in the app's API permissions. val scopes: ArrayList<String?> = object : ArrayList<String?>() { init { add( "user:email" ) } } provider.scopes = scopes // call signInWithGithubProvider() method // after clicking login Button loginBtn.setOnClickListener { if (TextUtils.isEmpty(githubEdit.text.toString())) { Toast.makeText( this , "Enter your github id" , Toast.LENGTH_LONG).show() } else { signInWithGithubProvider() } } } // To check if there is a pending result, call pendingAuthResult private fun signInWithGithubProvider() { // There's something already here! Finish the sign-in for your user. val pendingResultTask: Task<AuthResult>? = auth.pendingAuthResult if (pendingResultTask != null ) { pendingResultTask .addOnSuccessListener { // User is signed in. Toast.makeText( this , "User exist" , Toast.LENGTH_LONG).show() } .addOnFailureListener { // Handle failure. Toast.makeText( this , "Error : $it" , Toast.LENGTH_LONG).show() } } else { auth.startActivityForSignInWithProvider( /* activity= */ this , provider.build()) .addOnSuccessListener( OnSuccessListener<AuthResult?> { // User is signed in. // retrieve the current user firebaseUser = auth.currentUser!! // navigate to HomePageActivity after successful login val intent = Intent( this , HomePageActivity:: class .java) // send github user name from MainActivity to HomePageActivity intent.putExtra( "githubUserName" , firebaseUser.displayName) this .startActivity(intent) Toast.makeText( this , "Login Successfully" , Toast.LENGTH_LONG).show() }) .addOnFailureListener( OnFailureListener { // Handle failure. Toast.makeText( this , "Error : $it" , Toast.LENGTH_LONG).show() }) } } } |
Step 6: Create a new Empty Activity
Refer to this article Create New Activity in Android Studio and create an empty activity. Name the activity as HomePageActivity. Navigate to the app > res > layout > activity_home_page.xml and add the below code to that file. Below is the code for the activity_home_page.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < androidx.constraintlayout.widget.ConstraintLayout android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".HomePageActivity" > < LinearLayout android:id = "@+id/linearLayout" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_marginStart = "10dp" android:layout_marginTop = "10dp" android:layout_marginEnd = "10dp" android:orientation = "horizontal" app:layout_constraintEnd_toEndOf = "parent" app:layout_constraintStart_toStartOf = "parent" app:layout_constraintTop_toTopOf = "parent" > < TextView android:id = "@+id/headerId" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_marginTop = "10dp" android:text = "User Name :" android:textColor = "#06590A" android:textSize = "25sp" app:layout_constraintEnd_toEndOf = "parent" app:layout_constraintStart_toStartOf = "parent" app:layout_constraintTop_toTopOf = "parent" /> < TextView android:id = "@+id/id" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_margin = "10dp" android:layout_marginTop = "10dp" android:hint = "github Id" android:textAlignment = "center" android:textSize = "25sp" app:layout_constraintEnd_toEndOf = "parent" app:layout_constraintStart_toStartOf = "parent" app:layout_constraintTop_toTopOf = "parent" /> </ LinearLayout > < Button android:id = "@+id/logOut" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_marginTop = "456dp" android:layout_marginBottom = "20dp" android:gravity = "center" android:text = "Logout" android:textColor = "#fff" app:layout_constraintBottom_toBottomOf = "parent" app:layout_constraintEnd_toEndOf = "parent" app:layout_constraintStart_toStartOf = "parent" app:layout_constraintTop_toBottomOf = "@+id/linearLayout" /> </ androidx.constraintlayout.widget.ConstraintLayout > |
Go to the HomePageActivity.kt file and refer to the following code. Below is the code for the HomePageActivity.kt file.
Kotlin
import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView class HomePageActivity : AppCompatActivity() { var userName = "" private lateinit var githubUserName: TextView private lateinit var logoutBtn: Button override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_home_page) githubUserName = findViewById(R.id.id) logoutBtn = findViewById(R.id.logOut) userName = intent.getStringExtra( "githubUserName" )!! githubUserName.text = userName logoutBtn.setOnClickListener { val intent = Intent( this , MainActivity:: class .java) this .startActivity(intent) } } } |
Note: Don’t forget to Revoke all user tokens. This option will be shown when your application is ready and run once. Or may you see this option earlier?
Here is the final output.
Output:
Please Login to comment...