ユーザー セッションの管理

Firebase Authentication セッションは長期間有効です。ユーザーがログインするたびに、ユーザー認証情報が Firebase Authentication のバックエンドに送信され、Firebase ID トークン(JWT)および更新トークンと交換されます。Firebase ID トークンの有効期間は短く、1 時間で期限切れとなります。新しい ID トークンは、更新トークンを使用して取得できます。 更新トークンは、次のいずれかが発生した場合にのみ有効期限が切れます。

  • ユーザーが削除された
  • ユーザーが無効にされた
  • ユーザーのアカウントで大きな変更が検出された(パスワードやメールアドレスの更新など)

Firebase Admin SDK には、指定したユーザーの更新トークンを取り消す機能があります。さらに、ID トークンの取り消しを確認する API も使用できます。これらの機能により、ユーザー セッションをより細かく制御できます。SDK には、疑わしい状況でセッションが使用されないように制限を加えたり、起こり得るトークンの盗難から復旧させるためのメカニズムを追加したりする機能があります。

更新トークンを取り消す

既存の更新トークンの取り消しは、ユーザーがデバイスの紛失または盗難を報告したときなどに実行します。同様に、一般的な脆弱性を発見した場合や、アクティブなトークンの広範囲な漏えいが疑われる場合は、listUsers API を使用してすべてのユーザーを検索し、指定されたプロジェクトのトークンを取り消すことができます。

パスワードをリセットすると、ユーザーの既存のトークンも取り消されます。ただし、その場合、Firebase Authentication バックエンドは自動的に取り消しを処理します。 取り消されると、ユーザーはログアウトされ、再認証を促すプロンプトが表示されます。

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}`);
  });

Java

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))

Go

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 Authentication バックエンドからトークンのステータスを要求するしかありません。そのため、このチェックをサーバーで実行すると、ネットワークで追加のラウンドトリップを必要とする負荷の大きい処理となります。このネットワーク リクエストは、Admin SDK を使用してチェックを行うのではなく、取り消しを確認する Firebase セキュリティ ルールを設定することで回避できます。

Firebase セキュリティ ルールで ID トークンの取り消しを検出する

セキュリティ ルールを使用して ID トークンの取り消しを検出できるようにするには、まずユーザー固有のメタデータを保存する必要があります。

Firebase Realtime Database でユーザー固有のメタデータを更新する

更新トークンの取り消しのタイムスタンプを保存します。これは、Firebase セキュリティ ルールにより ID トークンの取り消しを追跡するために必要です。これにより、データベース内の効率的なチェックが可能になります。次のコードサンプルでは、前のセクションで取得した uid と取り消し時刻を使用します。

Node.js

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

Java

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 Authentication クライアント SDK によって提供される再認証 API を使用して再認証を求められるようにします。

お使いのプラットフォーム用の Admin SDK を初期化するには、設定ページの指示に沿って操作します。ID トークンの取得の例は、verifyIdToken セクションに示すとおりです。

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.
    }
  });

Java

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

Go

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!' })
      });
    }
  });
});