使用Firebase邮箱/密码认证时,访问令牌是否会自动刷新?
I'm using Firebase's email/password authentication method. After a user successfully logs in, I retrieve the access token using this code:
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 { // ... } } });
I'm wondering if this Firebase access token automatically refreshes in this scenario.
Great question! Let's break this down clearly:
Firebase does automatically refresh ID tokens for authenticated users—including those signed in with email/password. The SDK handles this background refresh automatically, so you don't have to manually trigger it every time the token expires (tokens are valid for 1 hour by default).
Looking at your specific code: when you call
getIdToken(true), thetrueparameter forces an immediate refresh, skipping any cached token. If you usegetIdToken(false)instead, the SDK will return the cached token if it's still valid, and only refresh it if it's expired or nearing expiration.Even if you don't call
getIdToken()again after the initial fetch, the Firebase Auth SDK will quietly refresh the token in the background once it's close to expiring. This means theFirebaseUserinstance will always have a valid token ready when you need it later.A key note: if the user's session is invalidated (e.g., they sign out, their account gets disabled, or their password is changed), the automatic refresh will fail. Make sure to handle these error cases in your callbacks to avoid unexpected behavior.
To wrap it up: yes, the token refreshes automatically in the background. Your code can either fetch a fresh token right away (with true) or use the cached valid token (with false) based on your needs.
内容的提问来源于stack exchange,提问作者Degoah

