-->

How would I return a Firebase custom token if the

2019-07-27 22:14发布

问题:

I'm using the Spark Framework hosted on Heroku and I have this in my main: method in my server

post("/token", (request, response) -> "Hello World");

That's working fine, however, I want to actually send a custom token, and not just "Hello World".

So, logically, I would need this:

FirebaseAuth auth = FirebaseAuth.getInstance();
String uid = UUID.randomUUID().toString();
post("/token", (request, response) -> auth.createCustomToken(uid));

However, createCustomToken returns a Task<String> and not a String. So, I have to do:

auth.createCustomToken(uid).addOnSuccessListener(new OnSuccessListener<String>() {
            @Override
            public void onSuccess(String s) {

            }
        });

However, in this form:

post("/token", (request, response) -> auth.createCustomToken(uid).addOnSuccessListener(new OnSuccessListener<String>() {
            @Override
            public void onSuccess(String token) {

            }
        }));

All I really still returned was a Task<String>. I need to return token from the onSuccess() method, but I can't since it's an inner class.

What can I do to solve this?

回答1:

I was running into a similar problem at Google App Engine. I had to verify a firebase token at server side but the response were sent back async from firebase. ( Verify Firebase Token at Google App Engine)

You can try the following code instead of using a OnSuccesListener

Task<String> authTask = FirebaseAuth.getInstance().createCustomToken(uid);

try {
    Tasks.await(authTask);
} catch (ExecutionException | InterruptedException e ) {
    log.severe(e.getMessage());
}

String myToken = authTask.getResult();


回答2:

This worked for me:

FirebaseAuth.getInstance().createCustomTokenAsync(UID).get()

It returns a custom token in a string. Got it from https://www.youtube.com/watch?v=Fi2dv6NcHWA