管理用戶會話

Firebase 驗證會話的壽命很長。每次使用者登入時,使用者憑證都會傳送到 Firebase 驗證後端並交換 Firebase ID 令牌 (JWT) 和刷新令牌。 Firebase ID 令牌的生命週期很短,只能持續一個小時;刷新令牌可用於檢索新的 ID 令牌。只有當發生以下情況之一時,刷新令牌才會過期:

  • 該用戶已被刪除
  • 該用戶已停用
  • 偵測到使用者的主要帳戶變更。這包括密碼或電子郵件地址更新等事件。

Firebase Admin SDK 提供了撤銷指定使用者的刷新令牌的功能。此外,還提供了用於檢查 ID 令牌撤銷的 API。借助這些功能,您可以更好地控制使用者會話。 SDK 提供了新增限制以防止在可疑情況下使用會話的功能,以及從潛在令牌盜竊中恢復的機制。

撤銷刷新令牌

當使用者報告裝置遺失或被竊時,您可以撤銷使用者的現有刷新令牌。同樣,如果您發現一般漏洞或懷疑活動代幣大規模洩漏,您可以使用listUsers API 尋找所有使用者並撤銷其指定項目的代幣。

密碼重設也會撤銷使用者現有的令牌;但是,在這種情況下,Firebase 驗證後端會自動處理撤銷。撤銷後,使用者將被登出並提示重新進行身份驗證。

以下是使用 Admin SDK 撤銷給定使用者的刷新令牌的範例實作。若要初始化 Admin SDK,請按照設定頁面上的說明進行操作。

Node.js

// Revoke all refresh tokens for a specified user for whatever reason.
// Retrieve the timestamp of the revocation, in seconds since the epoch.
getAuth()
  .revokeRefreshTokens(uid)
  .then(() => {
    return getAuth().getUser(uid);
  })
  .then((userRecord) => {
    return new Date(userRecord.tokensValidAfterTime).getTime() / 1000;
  })
  .then((timestamp) => {
    console.log(`Tokens revoked at: ${timestamp}`);
  });

爪哇

FirebaseAuth.getInstance().revokeRefreshTokens(uid);
UserRecord user = FirebaseAuth.getInstance().getUser(uid);
// Convert to seconds as the auth_time in the token claims is in seconds too.
long revocationSecond = user.getTokensValidAfterTimestamp() / 1000;
System.out.println("Tokens revoked at: " + revocationSecond);

Python

# Revoke tokens on the backend.
auth.revoke_refresh_tokens(uid)
user = auth.get_user(uid)
# Convert to seconds as the auth_time in the token claims is in seconds.
revocation_second = user.tokens_valid_after_timestamp / 1000
print('Tokens revoked at: {0}'.format(revocation_second))

client, err := app.Auth(ctx)
if err != nil {
	log.Fatalf("error getting Auth client: %v\n", err)
}
if err := client.RevokeRefreshTokens(ctx, uid); err != nil {
	log.Fatalf("error revoking tokens for user: %v, %v\n", uid, err)
}
// accessing the user's TokenValidAfter
u, err := client.GetUser(ctx, uid)
if err != nil {
	log.Fatalf("error getting user %s: %v\n", uid, err)
}
timestamp := u.TokensValidAfterMillis / 1000
log.Printf("the refresh tokens were revoked at: %d (UTC seconds) ", timestamp)

C#

await FirebaseAuth.DefaultInstance.RevokeRefreshTokensAsync(uid);
var user = await FirebaseAuth.DefaultInstance.GetUserAsync(uid);
Console.WriteLine("Tokens revoked at: " + user.TokensValidAfterTimestamp);

偵測 ID 令牌撤銷

由於 Firebase ID 令牌是無狀態 JWT,因此您只能透過從 Firebase 驗證後端請求令牌的狀態來確定令牌已被撤銷。因此,在伺服器上執行此檢查是一項昂貴的操作,需要額外的網路往返。您可以透過設定檢查撤銷的 Firebase 安全性規則(而不是使用 Admin SDK 進行檢查)來避免發出此網路請求。

在 Firebase 安全性規則中偵測 ID 令牌撤銷

為了能夠使用安全規則來偵測 ID 令牌吊銷,我們必須先儲存一些特定於使用者的元資料。

更新 Firebase 即時資料庫中的使用者特定元資料。

儲存刷新令牌撤銷時間戳記。這是透過 Firebase 安全規則追蹤 ID 令牌撤銷所必需的。這允許在資料庫內進行有效的檢查。在下面的程式碼範例中,使用上一節中取得的uid和撤銷時間。

Node.js

const metadataRef = getDatabase().ref('metadata/' + uid);
metadataRef.set({ revokeTime: utcRevocationTimeSecs }).then(() => {
  console.log('Database updated successfully.');
});

爪哇

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("metadata/" + uid);
Map<String, Object> userData = new HashMap<>();
userData.put("revokeTime", revocationSecond);
ref.setValueAsync(userData);

Python

metadata_ref = firebase_admin.db.reference("metadata/" + uid)
metadata_ref.set({'revokeTime': revocation_second})

新增對 Firebase 安全規則的檢查

若要強制執行此檢查,請設定一條沒有用戶端寫入存取權限的規則來儲存每個使用者的撤銷時間。可以使用上次撤銷時間的 UTC 時間戳進行更新,如前面的範例所示:

{
  "rules": {
    "metadata": {
      "$user_id": {
        // this could be false as it is only accessed from backend or rules.
        ".read": "$user_id === auth.uid",
        ".write": "false",
      }
    }
  }
}

任何需要經過身份驗證的存取的資料都必須配置以下規則。此邏輯僅允許具有未撤銷 ID 令牌的經過驗證的使用者存取受保護的資料:

{
  "rules": {
    "users": {
      "$user_id": {
        ".read": "auth != null && $user_id === auth.uid && (
            !root.child('metadata').child(auth.uid).child('revokeTime').exists()
          || auth.token.auth_time > root.child('metadata').child(auth.uid).child('revokeTime').val()
        )",
        ".write": "auth != null && $user_id === auth.uid && (
            !root.child('metadata').child(auth.uid).child('revokeTime').exists()
          || auth.token.auth_time > root.child('metadata').child(auth.uid).child('revokeTime').val()
        )",
      }
    }
  }
}

偵測 SDK 中的 ID 令牌撤銷。

在您的伺服器中,實作下列刷新令牌撤銷和 ID 令牌驗證邏輯:

當要驗證使用者的 ID 令牌時,必須將附加的checkRevoked布林標誌傳遞給verifyIdToken 。如果使用者的令牌被撤銷,則應在用戶端上登出使用者或要求使用者使用 Firebase 驗證用戶端 SDK 提供的重新驗證 API 重新進行驗證。

若要為您的平台初始化 Admin SDK,請按照設定頁面上的說明進行操作。 verifyIdToken部分中提供了檢索 ID 令牌的範例。

Node.js

// Verify the ID token while checking if the token is revoked by passing
// checkRevoked true.
let checkRevoked = true;
getAuth()
  .verifyIdToken(idToken, checkRevoked)
  .then((payload) => {
    // Token is valid.
  })
  .catch((error) => {
    if (error.code == 'auth/id-token-revoked') {
      // Token has been revoked. Inform the user to reauthenticate or signOut() the user.
    } else {
      // Token is invalid.
    }
  });

爪哇

try {
  // Verify the ID token while checking if the token is revoked by passing checkRevoked
  // as true.
  boolean checkRevoked = true;
  FirebaseToken decodedToken = FirebaseAuth.getInstance()
      .verifyIdToken(idToken, checkRevoked);
  // Token is valid and not revoked.
  String uid = decodedToken.getUid();
} catch (FirebaseAuthException e) {
  if (e.getAuthErrorCode() == AuthErrorCode.REVOKED_ID_TOKEN) {
    // Token has been revoked. Inform the user to re-authenticate or signOut() the user.
  } else {
    // Token is invalid.
  }
}

Python

try:
    # Verify the ID token while checking if the token is revoked by
    # passing check_revoked=True.
    decoded_token = auth.verify_id_token(id_token, check_revoked=True)
    # Token is valid and not revoked.
    uid = decoded_token['uid']
except auth.RevokedIdTokenError:
    # Token revoked, inform the user to reauthenticate or signOut().
    pass
except auth.UserDisabledError:
    # Token belongs to a disabled user record.
    pass
except auth.InvalidIdTokenError:
    # Token is invalid
    pass

client, err := app.Auth(ctx)
if err != nil {
	log.Fatalf("error getting Auth client: %v\n", err)
}
token, err := client.VerifyIDTokenAndCheckRevoked(ctx, idToken)
if err != nil {
	if err.Error() == "ID token has been revoked" {
		// Token is revoked. Inform the user to reauthenticate or signOut() the user.
	} else {
		// Token is invalid
	}
}
log.Printf("Verified ID token: %v\n", token)

C#

try
{
    // Verify the ID token while checking if the token is revoked by passing checkRevoked
    // as true.
    bool checkRevoked = true;
    var decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(
        idToken, checkRevoked);
    // Token is valid and not revoked.
    string uid = decodedToken.Uid;
}
catch (FirebaseAuthException ex)
{
    if (ex.AuthErrorCode == AuthErrorCode.RevokedIdToken)
    {
        // Token has been revoked. Inform the user to re-authenticate or signOut() the user.
    }
    else
    {
        // Token is invalid.
    }
}

回應客戶端上的令牌撤銷

如果透過 Admin SDK 撤銷令牌,用戶端會收到撤銷通知,且使用者需要重新進行身份驗證或登出:

function onIdTokenRevocation() {
  // For an email/password user. Prompt the user for the password again.
  let password = prompt('Please provide your password for reauthentication');
  let credential = firebase.auth.EmailAuthProvider.credential(
      firebase.auth().currentUser.email, password);
  firebase.auth().currentUser.reauthenticateWithCredential(credential)
    .then(result => {
      // User successfully reauthenticated. New ID tokens should be valid.
    })
    .catch(error => {
      // An error occurred.
    });
}

進階安全性:實施 IP 位址限制

偵測令牌盜竊的常見安全機制是追蹤請求 IP 位址來源。例如,如果請求始終來自相同 IP 位址(發出呼叫的伺服器),則可以強制執行單一 IP 位址會話。或者,如果您偵測到使用者的 IP 位址突然變更地理位置或收到來自可疑來源的請求,則可以撤銷使用者的代幣。

若要基於IP 位址執行安全性檢查,對於每個經過驗證的請求,請檢查ID 令牌,並在允許存取受限資料之前檢查請求的IP 位址是否與先前的受信任IP 位址相符或位於受信任範圍內。例如:

app.post('/getRestrictedData', (req, res) => {
  // Get the ID token passed.
  const idToken = req.body.idToken;
  // Verify the ID token, check if revoked and decode its payload.
  admin.auth().verifyIdToken(idToken, true).then((claims) => {
    // Get the user's previous IP addresses, previously saved.
    return getPreviousUserIpAddresses(claims.sub);
  }).then(previousIpAddresses => {
    // Get the request IP address.
    const requestIpAddress = req.connection.remoteAddress;
    // Check if the request IP address origin is suspicious relative to previous
    // IP addresses. The current request timestamp and the auth_time of the ID
    // token can provide additional signals of abuse especially if the IP address
    // suddenly changed. If there was a sudden location change in a
    // short period of time, then it will give stronger signals of possible abuse.
    if (!isValidIpAddress(previousIpAddresses, requestIpAddress)) {
      // Invalid IP address, take action quickly and revoke all user's refresh tokens.
      revokeUserTokens(claims.uid).then(() => {
        res.status(401).send({error: 'Unauthorized access. Please login again!'});
      }, error => {
        res.status(401).send({error: 'Unauthorized access. Please login again!'});
      });
    } else {
      // Access is valid. Try to return data.
      getData(claims).then(data => {
        res.end(JSON.stringify(data);
      }, error => {
        res.status(500).send({ error: 'Server error!' })
      });
    }
  });
});