Authenticate with Twitter Sign in

Victor Santander
FW Engineering
Published in
3 min readApr 15, 2019

Tired of writing the same authentication/registration code in all your apps? Tired of including a lot of fields to register on your app?

Keep reading to find out how to fix it with Twitter SDK and Firebase.

This article is the second article in a series which show how to sign in with an SDK (Google, Twitter, Facebook, etc). Here we’re going to look at the steps required to authenticate with Firebase using a Twitter account.

Server configuration

  • Open the Firebase console
  • Create a new project if you don’t have one including all the information requested
  • Enter in the Twitter developer portal and include your app (These steps will be quite long because you have to include some information, I took around nearly 1 hour, so please be patient, otherwise you will end like the guy in this image)
  • Once you have registered your app on the Twitter developer portal you will have an API key and API secret from your app, then in the Firebase console open the Auth section and active the Twitter auth specifying the tokens received from Twitter

Android configuration

implementation 'com.google.firebase:firebase-auth:x.x.x'
implementation 'com.firebaseui:firebase-ui-auth:x.x.x'
implementation 'com.twitter.sdk.android:twitter-core:x.x.x'

After the configuration is done, we are ready to code the solution.

Android project

  • In the application class of the project, in the onCreate method we initialise the Firebase and the Twitter SDK using the API key and the API secret.
// Init firebase
FirebaseApp.initializeApp(this)

// Twitter
val config = TwitterConfig.Builder(this)
.logger(DefaultLogger(Log.DEBUG))
.twitterAuthConfig(
TwitterAuthConfig(
BuildConfig.TWITTER_CONSUMER_KEY,
BuildConfig.TWITTER_CONSUMER_SECRET
)
)
.debug(BuildConfig.DEBUG)
.build()
Twitter.initialize(config)
  • Add the Twitter login Button in the layout, we use the button provided by the SDK.
<com.twitter.sdk.android.core.identity.TwitterLoginButton
android:id="@+id/btnTwitterLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sign_in_with_twitter"
/>
  • We set the login button callback in order to intercept if the login is a success or not. Also we pass the onActivityResult to the button.
btnTwitterLogin.callback = object : Callback<TwitterSession>() {

override fun success(result: Result<TwitterSession>?) {
handleLoginResponseWithTwitter(result?.data)
}

override fun failure(exception: TwitterException) {
handleLoginErrorWithTwitter(exception)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)

if (requestCode == TwitterSignInUtils.TWITTER_REQ_CODE){
btnTwitterLogin.onActivityResult(requestCode, resultCode, data)
}
}
  • Once the user press on Twitter button and enter the credentials then we handle the result if is success, in that case with the results we use the following code in order to sign in with Firebase
fun handleLoginResponse(data: Any?) {
val session = data as TwitterSession
val credential = TwitterAuthProvider.getCredential(
session.authToken.token,
session.authToken.secret
)

firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if
(task.isSuccessful && firebaseAuth.currentUser != null) {
Log.d("login ok")
} else {
Log.e("login error: ${task.exception}")
}
}
}
  • Once the login process is finished, to logout is very simple we do it using this code
FirebaseAuth.getInstance().signOut()
TwitterCore.getInstance().sessionManager.clearActiveSession()
  • And finally in order to know if any user is logged in, if the instance is different than null, it means that any user is logged in
fun isUserLoggedIn(): Boolean = firebaseAuth.currentUser != null

Here you can see the example application that we created.

Thanks for reading this article, hope you find this useful.

--

--