Twitter Firebase Authentication in Android: In 4 easy steps.

In today’s world, many popular Android apps have twitter firebase authentication implemented. This makes it easier for their users to sign in directly to their app without creating an account manually. I’ve found that most developers who are starting to learn Android development also want to add this feature to their app. But there are very few resources available online which tells us how to implement twitter firebase authentication so to help many of you out, I am creating this post. In this blog post, we will be implementing the Twitter login authentication using Firebase in an Android application.
For implementing the twitter firebase authentication and to make the Twitter login work inside your app you must have the Twitter (X) application installed on your smartphone otherwise the login will not work.
But before diving into the code we first have to create a new project on the Firebase console as well as on the Twitter developers page.
Creating a Firebase Project
First, head over to the Firebase website and click on the “+ “ icon to create a new project.

On the next page enter the name of your app and then select “Set up Google Analytics for my project” and click on “Continue”. After that, it will ask to choose a Google Analytics account. If you have one then you can choose that in the drop-down, otherwise create a new one and then click on “Create Project”.

Now that we have created our Firebase project, we also have to create an app on the Twitter developers page. To turn on the Twitter sign-in feature inside the Firebase Authentication section, we will need an API Key and an API Secret which we can get from the Twitter developers page after creating an app. But first, let’s copy the callback URL by clicking on the Authentication section in the left inside the Firebase console, select the sign-in method tab to choose the “Twitter “ option, and copy the callback URL.

Creating an app on Twitter Developers
Go to the Twitter developers page and click on “ create an app “ to create a new project.

Then you have to fill in all of the details about your app like the name, website, description, privacy policy, etc. Make sure that you check the “Enable Sign in with Twitter” option and also enter the URL of your privacy policy page because it is really important. I will tell you why later in this blog post.
Also, it is mandatory to enter the callback URL here, which we have already copied from the Firebase console as mentioned above. If you have not copied the callback URL then please do so, then click on “Create” and accept the terms and conditions.
Now to get the API key and API Secret, select the "Keys and Tokens" tab at the top, copy these two keys, and paste it on to your Firebase Twitter sign-in method page back at the Firebase console, and click "save".

Setting up the Android Studio for Firebase
Now that we are done with all the required setup work, you can now create a new Android Studio project. After that, let’s add the required dependencies and google-services.json file to your project. For that click on the Android icon as shown in the figure below and follow the first 3 steps. You can skip the 4th step.

Follow the steps mentioned on the screen until you get to the end which will set up your Android Studio project for using the Firebase services. It’s really easy and it will take around 5–10 minutes to complete.
Note: To get the Debug signing certificate SHA-1 key you have to run the following command. To make the command work you must have Java JDK and OpenSSL installed on your system.
//Debug keystore
keytool -list -v -alias androiddebugkey -keystore C:\Users\<your user name>\.android\debug.keystore
Make sure that you are inside your Java JDK’s bin folder while running this command otherwise the command will not work and also replace <your user name> with your username.
Implementing the twitter firebase authentication in android
Now that we have everything set up we are ready to write the code and implement the twitter firebase authentication feature on to our Android application. First, add the Twitter dependencies which can be found on the twitter-archive page on Github and follow the “ Add Twitter Kit Dependencies “ step only, to get twitter dependencies and then come back here.
Then add the following two string values into your strings.xml file. Here you have to add your API Key (Consumer Key) and API Secret (Consumer Secret) replacing the “XXXXXXX”.
- Adding internet permission in your AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
- Adding the Twitter sign-in button to activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginActivity">
<!--Twitter Login Button-->
<com.twitter.sdk.android.core.identity.TwitterLoginButton
android:id="@+id/twitter_login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<ProgressBar
android:id="@+id/indeterminateProgressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:indeterminate="true"
android:visibility="invisible"
android:layout_marginTop="-7dp"/>
</RelativeLayout>
- Adding Twitter sign-in code to LoginActivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.TwitterAuthProvider;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.Twitter;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterConfig;
import com.twitter.sdk.android.core.TwitterCore;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private TwitterLoginButton mTwitterBtn;
private ProgressBar mIndeterminateProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//This code must be entering before the setContentView to make the twitter login work...
TwitterAuthConfig mTwitterAuthConfig = new TwitterAuthConfig(getString(R.string.twitter_consumer_key),
getString(R.string.twitter_consumer_secret));
TwitterConfig twitterConfig = new TwitterConfig.Builder(this)
.twitterAuthConfig(mTwitterAuthConfig)
.build();
Twitter.initialize(twitterConfig);
setContentView(R.layout.activity_main);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
mTwitterBtn = findViewById(R.id.twitter_login_button);
mIndeterminateProgressBar = findViewById(R.id.indeterminateProgressBar);
mAuthListener = new FirebaseAuth.AuthStateListener(){
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth){
if (firebaseAuth.getCurrentUser() != null){
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
}
};
UpdateTwitterButton();
mTwitterBtn.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
Toast.makeText(LoginActivity.this, "Signed in to twitter successful", Toast.LENGTH_LONG).show();
signInToFirebaseWithTwitterSession(result.data);
mTwitterBtn.setVisibility(View.VISIBLE);
mIndeterminateProgressBar.setVisibility(View.VISIBLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
@Override
public void failure(TwitterException exception) {
Toast.makeText(LoginActivity.this, "Login failed. No internet or No Twitter app found on your phone", Toast.LENGTH_LONG).show();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
mIndeterminateProgressBar.setVisibility(View.GONE);
UpdateTwitterButton();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mTwitterBtn.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
updateUI();
}
mAuth.addAuthStateListener(mAuthListener);
}
private void updateUI() {
Toast.makeText(LoginActivity.this, "You're logged in", Toast.LENGTH_LONG);
//Sending user to new screen after successful login
Intent mainActivity = new Intent(LoginActivity.this, LoginActivity.class);
startActivity(mainActivity);
finish();
}
@Override
protected void onDestroy(){
super.onDestroy();
mAuth.removeAuthStateListener(mAuthListener);
}
private void UpdateTwitterButton(){
if (TwitterCore.getInstance().getSessionManager().getActiveSession() == null){
mTwitterBtn.setVisibility(View.VISIBLE);
}
else{
mTwitterBtn.setVisibility(View.GONE);
}
}
private void signInToFirebaseWithTwitterSession(TwitterSession session){
AuthCredential credential = TwitterAuthProvider.getCredential(session.getAuthToken().token,
session.getAuthToken().secret);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Toast.makeText(LoginActivity.this, "Signed in firebase twitter successful", Toast.LENGTH_LONG).show();
if (!task.isSuccessful()){
Toast.makeText(LoginActivity.this, "Auth firebase twitter failed", Toast.LENGTH_LONG).show();
}
}
});
}
}
- Adding a logout button to activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--Logout Button-->
<Button
android:id="@+id/logout_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="@drawable/ic_launcher_foreground"
android:text="Logout"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
- Adding code to MainActivity.java sign out the user.
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.twitter.sdk.android.core.SessionManager;
import com.twitter.sdk.android.core.TwitterCore;
import com.twitter.sdk.android.core.TwitterSession;
public class MainActivity extends AppCompatActivity {
Button logoutBtn;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//Firebase Auth
mAuth = FirebaseAuth.getInstance();
//Logout Btn
logoutBtn = findViewById(R.id.logout_button);
logoutBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SessionManager<TwitterSession> sessionManager = TwitterCore.getInstance().getSessionManager();
if (sessionManager.getActiveSession() != null){
sessionManager.clearActiveSession();
mAuth.signOut();
}
mAuth.signOut();
updateUI();
}
});
}
@Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
updateUI();
}
}
private void updateUI() {
Toast.makeText(MainActivity.this, "You're logged out", Toast.LENGTH_LONG);
Intent mainActivity = new Intent(MainActivity.this, LoginActivity.class);
startActivity(mainActivity);
finish();
}
}
Solving the Twitter email field appearing empty in Firebase Authentication
Now after implementing all the above code into your Android project, if you run your app and log in by using twitter firebase authentication with your twitter account credentials then the details of that user will be available inside your Firebase Authentication section under “Users”. But you will notice that the email of the user is not available or is otherwise blank.


This option will only be accessible to you if you have entered a privacy policy link to your app on the Twitter developers page. But after making the change, the time tie the user signs in, you will see their email address inside the Firebase console.

Final Output:
https://youtube.com/shorts/aMBu-N96iLY
To get the full project you can go to the TwitterAuth on Github and can download it from there.
Thanks for reading and if you like our twitter firebase authentication blog then share it with others.





