David Armendariz
David Armendariz

Reputation: 1759

How to authenticate to Firebase using Python?

I am building a Web App with Python and I would like to authenticate users. The pyrebase package seems to be outdated and it generates dependency errors so I cannot use it. I know that there is a function from the firebase-admin API that works like this:

from firebase import auth
email = [email protected]
user = auth.get_user_by_email(email)

But what if this user has a password? I would like to check if the both the email and the password are provided correctly. Thanks in advance.

Upvotes: 3

Views: 6694

Answers (2)

ganiular
ganiular

Reputation: 629

Firebase Admin SDK doesn’t provide an API to validate and/or authenticate a user by their password.

However, Firebase provides the Firebase Auth REST API for this purpose. To use the REST API, you need to obtain your Web API Key from the Firebase console.

To Locate the Web API Key

Navigate to Project Settings from Firebase console, then find Web API Key on the General tab. The Web Api key is auto generated whenever you add app to your firebase project. You can also go to an app settings to find apiKey from firebaseConfig

Implement Authentication

Suppose you want to implement user sign in

def sign_in_with_email_and_password(email, password, return_secure_token=True):
    payload = json.dumps({"email":email, "password":password, "return_secure_token":return_secure_token})
    FIREBASE_WEB_API_KEY = 'the web API key here' 
    rest_api_url = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword"

    r = requests.post(rest_api_url,
                  params={"key": FIREBASE_WEB_API_KEY},
                  data=payload)

    return r.json()

References

Upvotes: 4

Frank van Puffelen
Frank van Puffelen

Reputation: 598765

The Firebase Admin SDK does not have the concept of a current user, so there's no API to "sign in" a user based on their credentials.

Since you're building a web app, the usual flow is to use the Firebase JavaScript SDK in your client-side code to sign the user in. If needed you can then send the ID token from the client to your Python code on the server, and perform user-based operations there.

Upvotes: 2

Related Questions