How would I return a Firebase custom token if the generation of the custom token is asynchronous?

我与影子孤独终老i 提交于 2019-12-11 07:54:29

问题


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



来源:https://stackoverflow.com/questions/42467781/how-would-i-return-a-firebase-custom-token-if-the-generation-of-the-custom-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!