h4v3st
h4v3st

Reputation: 17

Handling Firebase auth authentication

I need some help understanding if I am handling the authentication/authorization correctly with Firebase Auth, JS and Python.

Once the user has signed in, I capture the idToken and create a cookie in the browser:

firebase.auth().signInWithEmailAndPassword(email, pass)
.then(({user}) => {
    return user.getIdToken().then((idToken) => {
        if (idToken) {
            document.cookie = "token=" + idToken;
            window.location.assign('/profile');
        } else {
            document.cookie = "token="
        }
    })                    
})
.catch((error) => {
    //handle error here
});

The route /profile should be protected so I created a decorator and I retrieve the cookie and verify it:

id_token = request.cookies.get("token")

if not id_token:
    return redirect(url_for('login'))
try:
    decoded_token = auth.verify_id_token(id_token)
    uid = decoded_token['uid']
except Exception as e:
    print("Exception: {}".format(e))
    return redirect(url_for('login'))

This is working so far but I want to see if this is the ideal situation from a security perspective. Also, what about the onAuthStateChanged? How should I handle it in the case above?

Upvotes: 1

Views: 551

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

Firebase SDKs send the ID token with each request in the Authorization header, so sending it in a cookie is not going to more or less dangerous than that.

Instead of determining the token in signInWithEmailAndPassword though, I'd instead monitor ID token generation by listening to onIdTokenChanged events and using that moment to update your cookie.

Upvotes: 1

Related Questions