用Java解码Firebase令牌

时间:2019-02-03 18:23:25

标签: java firebase firebase-authentication firebase-admin

我正在尝试在后端验证/解码令牌,然后从解码的令牌中检索用户UID。令牌由客户端生成为字符串。后端成功检索/设置了Firebase数据,这使我相信Firebase正在正确初始化,因此这不会成为问题。但是,在运行时,似乎会出现导致崩溃的错误。

代码:

public static void main(String[] args) throws IOException, ExecutionException, InterruptedException, FirebaseAuthException {
        File credentialsFile = getFile();

        FileInputStream serviceAccount = new FileInputStream(credentialsFile);

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .setDatabaseUrl("***")
                .build();

        FirebaseApp.initializeApp(options);

        String idToken = "***";

        //LINE 43 IS BELOW
        FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdToken(idToken);
        String uid = decodedToken.getUid();

        System.out.println("UID: " + uid);
    }

错误:

Exception in thread "main" java.lang.IllegalArgumentException
    at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:108)
    at com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:37)
    at com.google.api.client.json.webtoken.JsonWebSignature$Parser.parse(JsonWebSignature.java:599)
    at com.google.firebase.auth.FirebaseToken.parse(FirebaseToken.java:44)
    at com.google.firebase.auth.FirebaseAuth$4.execute(FirebaseAuth.java:484)
    at com.google.firebase.auth.FirebaseAuth$4.execute(FirebaseAuth.java:477)
    at com.google.firebase.internal.CallableOperation.call(CallableOperation.java:36)
    at com.google.firebase.auth.FirebaseAuth.verifyIdToken(FirebaseAuth.java:441)
    at com.google.firebase.auth.FirebaseAuth.verifyIdToken(FirebaseAuth.java:415)
    at App.main(App.java:43)

FAILURE: Build failed with an exception.

1 个答案:

答案 0 :(得分:1)

解决方案:

问题在于hiranya-jayathilaka所指出的从客户端生成令牌的方式。这就是我生成令牌的方式:

String idToken = FirebaseInstanceId.getInstance().getToken();

这是应根据docs生成的方式:

FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
            mUser.getIdToken(true)
                    .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
                        public void onComplete(@NonNull Task<GetTokenResult> task) {
                            if (task.isSuccessful()) {
                                String idToken = task.getResult().getToken();
                                // Send token to your backend via HTTPS
                                // ...
                            } else {
                                // Handle error -> task.getException();
                            }
                        }
                    });