Search code examples
firebasegoogle-cloud-firestorefirebase-security

firebase security rules , how deny permission after change password


I'm building a web app and I'm using firebase to store data, I'm trying to make the user log out on to all devices when a password change or deny the user from "read" and "write" on firestore rules that are already authenticated on a different device but the user already changed the password.

I want to do this because in case a user account gets compromised and the original user change the password, the Intruder will still have access to read and write on the database if stay logging

Revoke refresh tokens Password resets also revoke a user's existing tokens; however, the Firebase Authentication backend handles the revocation automatically in that case. On revocation, the user is signed out and prompted to reauthenticate.

I didn't understand how to work with tokens, maybe there is a way to check "if firebase token === user client token" to see if a user on another device using the old token and deny write and read after a password change.

this is what my code looks like:

//reset password :

const resetPass = () =>{
    let newPassword = "testing3";

    updatePassword(user, newPassword).then(() => {
        console.log('password updated = '+ newPassword)
        logout () //logout logic

    }).catch((error) => {
        console.log('password not updated '+ error)
    })
}

firestore rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

sorry if I'm missing something, I'm still learning, thanks in advance.


Solution

  • In some scenarios like deleting the user account or changing the user password, we consider revoking the refresh tokens of the user. In such cases, Firebase automatically handles the token revocation. Once a refresh token has been revoked this way, it cannot be used to obtain new ID tokens. Therefore in time users will be prompted to sign in again, and obtain a new pair of ID and refresh tokens.

    Therefore, you can modify the security rules to compare the ID token issue times against the revocation times stored in the database. You may design your security rules by matching the auth.uid variable and the user ID on the requested data in the following manner:

    service cloud.firestore {
      match /databases/{database}/documents {
        // Make sure the uid of the requesting user matches name of the user
        // document. The wildcard expression {userId} makes the userId variable
        // available in rules.
        match /users/{userId} {
          allow read, write: if request.auth != null && request.auth.uid == userId;
        }
      }
    }
    

    You may also refer to the documentation.