จัดการเซสชันของผู้ใช้

เซสชันการตรวจสอบสิทธิ์ Firebase คงอยู่นาน ทุกครั้งที่ผู้ใช้ลงชื่อเข้าใช้ ระบบจะส่งข้อมูลเข้าสู่ระบบของผู้ใช้ไปยังแบ็กเอนด์การตรวจสอบสิทธิ์ Firebase และแลกเปลี่ยนกับโทเค็นรหัส Firebase (JWT) และโทเค็นการรีเฟรช โทเค็นรหัส Firebase มีอายุสั้น และมีอายุ 1 ชั่วโมง คุณจะใช้โทเค็นการรีเฟรชเพื่อเรียกโทเค็นรหัสใหม่ได้ โทเค็นการรีเฟรชจะหมดอายุก็ต่อเมื่อเกิดสิ่งใดสิ่งหนึ่งต่อไปนี้

  • ผู้ใช้ถูกลบแล้ว
  • ผู้ใช้ถูกปิดใช้งาน
  • ตรวจพบการเปลี่ยนแปลงที่สำคัญในบัญชีสำหรับผู้ใช้ ซึ่งรวมถึงการดำเนินการต่างๆ เช่น การอัปเดตรหัสผ่านหรืออีเมล

Firebase Admin SDK ให้คุณเพิกถอนโทเค็นการรีเฟรชสำหรับผู้ใช้ที่ระบุได้ นอกจากนี้ยังมี 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}`);
  });

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

ตรวจหาการเพิกถอนโทเค็นรหัส

เนื่องจากโทเค็นรหัส Firebase เป็น JWT แบบไม่เก็บสถานะ คุณระบุโทเค็นให้เพิกถอนได้โดยการขอสถานะของโทเค็นจากแบ็กเอนด์การตรวจสอบสิทธิ์ Firebase เท่านั้น ด้วยเหตุนี้ การตรวจสอบนี้บนเซิร์ฟเวอร์ของคุณเป็นการดำเนินการที่มีค่าใช้จ่ายสูง ทำให้ต้องใช้การส่งข้อมูลไปกลับของเครือข่ายเพิ่มเติม คุณหลีกเลี่ยงการส่งคำขอเครือข่ายนี้ได้โดยตั้งกฎการรักษาความปลอดภัยของ Firebase ที่ตรวจสอบการเพิกถอนแทนการใช้ Admin SDK เพื่อตรวจสอบ

ตรวจหาการเพิกถอนโทเค็นรหัสในกฎการรักษาความปลอดภัยของ Firebase

เราต้องจัดเก็บข้อมูลเมตาเฉพาะผู้ใช้บางส่วนก่อน จึงจะตรวจจับการเพิกถอนโทเค็นรหัสโดยใช้กฎความปลอดภัยได้

อัปเดตข้อมูลเมตาเฉพาะผู้ใช้ในฐานข้อมูลเรียลไทม์ของ Firebase

บันทึกการประทับเวลาการเพิกถอนโทเค็นการรีเฟรช ซึ่งจำเป็นสำหรับการติดตามการเพิกถอนโทเค็นรหัสผ่านกฎการรักษาความปลอดภัยของ Firebase ซึ่งช่วยให้การตรวจสอบภายในฐานข้อมูลมีประสิทธิภาพ ในตัวอย่างโค้ดด้านล่าง ให้ใช้ 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",
      }
    }
  }
}

ข้อมูลใดๆ ที่ต้องใช้การเข้าถึงที่ได้รับการตรวจสอบสิทธิ์จะต้องมีการกำหนดค่ากฎต่อไปนี้ ตรรกะนี้อนุญาตเฉพาะผู้ใช้ที่ตรวจสอบสิทธิ์แล้วซึ่งมีโทเค็นรหัสที่ยังไม่เพิกถอน ให้เข้าถึงข้อมูลที่มีการป้องกันได้

{
  "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

ใช้ตรรกะต่อไปนี้ในการเพิกถอนโทเค็นการรีเฟรชและการตรวจสอบโทเค็นรหัสในเซิร์ฟเวอร์ของคุณ

เมื่อโทเค็นรหัสของผู้ใช้ได้รับการยืนยันแล้ว จะต้องส่งแฟล็กบูลีน checkRevoked เพิ่มเติมไปยัง verifyIdToken หากมีการเพิกถอนโทเค็นของผู้ใช้ ควรให้ผู้ใช้ออกจากระบบในไคลเอ็นต์หรือขอให้ตรวจสอบสิทธิ์อีกครั้งโดยใช้ API การตรวจสอบสิทธิ์ซ้ำซึ่งมีให้โดย SDK ของไคลเอ็นต์การตรวจสอบสิทธิ์ Firebase

หากต้องการเริ่มต้น Admin SDK สำหรับแพลตฟอร์ม โปรดทำตามวิธีการในหน้าการตั้งค่า ตัวอย่างการเรียกโทเค็นรหัสอยู่ในส่วน 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 ให้ตรวจสอบโทเค็นรหัสทุกคำขอที่ตรวจสอบสิทธิ์แล้ว และตรวจสอบว่าที่อยู่ 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!' })
      });
    }
  });
});