在 Java 中解码 Firebase 令牌

Decode Firebase token in Java

我正在尝试 verify/decode 我后端的令牌,然后从解码的令牌中检索用户 UID。令牌由客户端生成为字符串。后端成功 retrieves/sets 数据到 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.execute(FirebaseAuth.java:484)
    at com.google.firebase.auth.FirebaseAuth.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.

解法:

正如 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();
                            }
                        }
                    });