Firebase auth JS with Flask

Viewed 655

I am struggling to understand Firebase authentication on the client/server side and have the question below.

I have a login.html page with a login-form and submit button. On the button click event, I have a JavaScript to do some client validation and perform the authentication):

btnSignIn.addEventListener('click', e => {
    // Get email/pass
    const email = inputEmail.value;
    const pass = inputPassword.value;
    /* to-do some validation and then sign in */
    // Sign in
    const promise = firebase.auth().signInWithEmailAndPassword(email, pass)
    promise.catch(e => console.log(e.message))
    }            
});

This is working great so far. Now, once the user has logged in, I want to redirect to home.html page but since this page should be protected by authorized users, do I need to send the token to the server (which is a Flask app)?

How do I send the token from JS to my Flask app? I saw in the Firebase docs that the way to go is via ajax. From the documentation, this is how I should send the token but I am not sure how to implement it.

firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
  // Send token to your backend via HTTPS
  // ...
}).catch(function(error) {
  // Handle error
});

My test Flask app:

@app.route('/')
@app.route('/home')
def home():
    return render_template("home.html")

@app.route('/login', methods=['GET', 'POST'])
def login():
    return render_template("login.html")
1 Answers

You cannot simply transfer the token from your js code into flask.

What I suggest you do is implement firebase in your backend python code instead of your frontend js code. To start using the python firebase sdk, I recommend either using the docs. That link points to the authentication docs, since your question is authentication related. You should select python as the type of code you would like to work with when viewing the docs.

Here is a youtube video as well on firebase authentication with flask that I really liked: https://www.youtube.com/watch?v=FCw5PFDb99k

Related