1

I'm working with firebase and angularfire2 which allows authentication with Facebook, Google+ and Twitter.

Now when a user authenticates like this, I get a response looking like the following.

{
"uid":"someUID",
"displayName":"ivaro18",
"photoURL":"https://lh3.googleusercontent.com/-myPicture/photo.jpg",
"email":"myEmail@gmail.com",
"emailVerified":true,
"isAnonymous":false,
"apiKey":"aUUIDApiKey",
"appName":"[DEFAULT]",
"authDomain":"mydemo.firebase.com",
"stsTokenManager":{
    "apiKey":"aUUIDApiKey",
    "refreshToken":"AHugeRefreshToken",
    "accessToken":"aHugeAccessToken",
    "expirationTime":1481297860666
},
"redirectEventId":null
}

The authentication works and the user data can be retrieved (left out providerData because it wasn't usefull in the JSON - won't be used)

I will send this uid or apiKey to my REST API (via Angular2's http.post), but to prevent man-in-the-middle attacks I want to validate the token.

So (edit: added the if and isComplete

    @JvmStatic fun main(args: Array<String>) {
        println("yes")
        val options = FirebaseOptions.Builder()
                .setServiceAccount(
                        FileInputStream("C:/Users/ivaro18/firebase.json")
                ).setDatabaseUrl("https://myDemo.firebaseio.com")
                .build()
        FirebaseApp.initializeApp(options)

        if(
        FirebaseAuth.getInstance().verifyIdToken("whatToken?")
                .addOnSuccessListener(OnSuccessListener<FirebaseToken>() {
                    @Override
                    fun onSuccess(decodedToken: FirebaseToken) {
                        val uid = decodedToken.getUid()
                        println("UID:::" + uid)
                    }
                })
                .addOnFailureListener(OnFailureListener() {
                    @Override
                    fun onFailure(e: Exception) {
                        e.printStackTrace()
                    }
                })
                .addOnCompleteListener(OnCompleteListener<FirebaseToken>() {
                    @Override
                    fun onComplete(token: FirebaseToken) {
                        println("Token: " + token)
                    }
        }).isComplete()) {
           println("verification completed");
        }
        println("ok")
    }

But this code outputs (Kotlin btw, almost same syntax as Java and it can run Java code)

yes
verficiation completed
ok

and then terminates after a while. I'd expect one of the listeners to fire? What is wrong with the code?

And what ID from that JSON array should I be validating within the FirebaseAuth?

edit

The uid part of the JSON is the same UID mentioned in the Firebase Authentication page (shown below)

Firebase Console

I want to check if the UID is equal to the UID on the console. (preferrably by sending the apiKey and accessToken but just checking if the uid is the same would be sufficient for now.

Ivar Reukers
  • 7,560
  • 9
  • 56
  • 99
  • If I had to guess I would suspect that the `FirebaseAuth` instance does not keep the main thread alive until the listeners have been triggered (and hence your program terminates after the second `println`). Have you tried adding a `while` loop to wait until the operation is done (e.g.: using [`isComplete`](https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/tasks/Task.html#isComplete())? – UnholySheep Dec 12 '16 at 11:10
  • Wrapping the statement in an `if(.....verfifyToken........isComplete()){ println("complete"); }` prints `yes` `complete` `ok` I'll edit the question with new code – Ivar Reukers Dec 12 '16 at 11:16
  • `isSuccesful` returns `false` with every `id` found within the JSON object – Ivar Reukers Dec 12 '16 at 11:18
  • Here is a java example: http://stackoverflow.com/questions/38418472/how-do-i-secure-my-google-cloud-endpoints-apis-with-firebase-token-verification/38423163#38423163 – Stefan Dec 12 '16 at 14:43

1 Answers1

2

Try this:

import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseToken
import com.google.firebase.tasks.Task
import com.google.firebase.tasks.Tasks
import java.io.FileInputStream

class Firebase {
val options = FirebaseOptions.Builder()
    .setServiceAccount(
        FileInputStream("your/url/to/firebase.json")
    ).setDatabaseUrl("https://your-application.firebaseio.com")
    .build()

    fun validateToken(accessToken: String) {
        val firebaseAuth = FirebaseAuth.getInstance(FirebaseApp.initializeApp(options))

        val authTask: Task<FirebaseToken> = firebaseAuth.verifyIdToken(accessToken)
        try{
            Tasks.await(authTask)
        } catch (e: Exception) {
            //handle exception
        }
        // retrieve uid/email/name
        authTask.getResult().uid
    }
}

And like Stefan said, take a look at this Java example.

Community
  • 1
  • 1