Authenticate users with Firebase Stay organized with collections Save and categorize content based on your preferences.
Region ID
TheREGION_ID is an abbreviated code that Google assignsbased on the region you select when you create your app. The code does notcorrespond to a country or province, even though some region IDs may appearsimilar to commonly used country and province codes. For apps created after February 2020,REGION_ID.r is included in App Engine URLs. For existing apps created before this date, the region ID is optional in the URL.
Learn moreabout region IDs.
Add a user sign-in flow to your web service that usesFirebase Authentication.
In this step of the guide, you update your web service to authenticate users andto retrieve and display a user's own information after they authenticate.Note that, for this step, the site request times will still be global rather thanuser-specific.
Before you begin
If you have completed all the previous steps in this guide, skip this section.Otherwise, complete one of the following:
Start fromBuild a Python 3 Appand complete all the steps leading up to this one.
If you already have aGoogle Cloud project,you can continue by downloading a copy of the web service and adding Firebase:
Download the sample application repository usingGit:
gitclonehttps://github.com/GoogleCloudPlatform/python-docs-samplesAlternatively, you candownload the sample as a zip file and then extract it.
Navigate to the directory that contains a copy of the files from theprevious step:
cdpython-docs-samples/appengine/standard_python3/building-an-app/building-an-app-2
Add Firebase authentication methods
Firebase provides JavaScript methods and variables that you can useto configure sign-in behavior for your web service. For this web service,add a sign out function, a variable that configures the sign in UI,and a function controlling what changes when a user signs in or out.
To add the behaviors required for an authentication flow, replace yourstatic/script.js file's current event listener method with the following code:
window.addEventListener('load',function(){document.getElementById('sign-out').onclick=function(){firebase.auth().signOut();};// FirebaseUI config.varuiConfig={signInSuccessUrl:'/',signInOptions:[// Comment out any lines corresponding to providers you did not check in// the Firebase console.firebase.auth.GoogleAuthProvider.PROVIDER_ID,firebase.auth.EmailAuthProvider.PROVIDER_ID,//firebase.auth.FacebookAuthProvider.PROVIDER_ID,//firebase.auth.TwitterAuthProvider.PROVIDER_ID,//firebase.auth.GithubAuthProvider.PROVIDER_ID,//firebase.auth.PhoneAuthProvider.PROVIDER_ID],// Terms of service url.tosUrl:'<your-tos-url>'};firebase.auth().onAuthStateChanged(function(user){if(user){// User is signed in, so display the "sign out" button and login info.document.getElementById('sign-out').hidden=false;document.getElementById('login-info').hidden=false;console.log(`Signed in as${user.displayName} (${user.email})`);user.getIdToken().then(function(token){// Add the token to the browser's cookies. The server will then be// able to verify the token against the API.// SECURITY NOTE: As cookies can easily be modified, only put the// token (which is verified server-side) in a cookie; do not add other// user information.document.cookie="token="+token;});}else{// User is signed out.// Initialize the FirebaseUI Widget using Firebase.varui=newfirebaseui.auth.AuthUI(firebase.auth());// Show the Firebase login button.ui.start('#firebaseui-auth-container',uiConfig);// Update the login state indicators.document.getElementById('sign-out').hidden=true;document.getElementById('login-info').hidden=true;// Clear the token cookie.document.cookie="token=";}},function(error){console.log(error);alert('Unable to log in: '+error)});});Notice that theonAuthStateChanged() method, which controls what changeswhen a user signs in or out, stores the user's ID token as a cookie.This ID token is a unique token that Firebase generatesautomatically when a user successfully signs in, and is used by the serverto authenticate the user.
Update your web service to use tokens
Next, verify users on the server using their unique Firebase ID token, thendecrypt their token so that you can print their data back to them.
To use the Firebase ID token:
Retrieve, verify, and decrypt the token in the
rootmethod of yourmain.pyfile:Tip: Make sure to importfromflaskimportFlask,render_template,requestfromgoogle.auth.transportimportrequestsfromgoogle.cloudimportdatastoreimportgoogle.oauth2.id_tokenfirebase_request_adapter=requests.Request()@app.route("/")defroot():# Verify Firebase auth.id_token=request.cookies.get("token")error_message=Noneclaims=Nonetimes=Noneifid_token:try:# Verify the token against the Firebase Auth API. This example# verifies the token on each page load. For improved performance,# some applications may wish to cache results in an encrypted# session store (see for instance# http://flask.pocoo.org/docs/1.0/quickstart/#sessions).claims=google.oauth2.id_token.verify_firebase_token(id_token,firebase_request_adapter)exceptValueErrorasexc:# This will be raised if the token is expired or any other# verification checks fail.error_message=str(exc)# Record and fetch the recent times a logged-in user has accessed# the site. This is currently shared amongst all users, but will be# individualized in a following step.store_time(datetime.datetime.now(tz=datetime.timezone.utc))times=fetch_times(10)returnrender_template("index.html",user_data=claims,error_message=error_message,times=times)requestfrom Flask so that you can fetch thecookie containing the user's ID token.Ensure that your
requirements.txtfile includes all necessary dependencies:Flask==3.0.0google-cloud-datastore==2.15.1google-auth==2.17.3requests==2.28.2
Test your web service
Test your web service by running it locally in a virtual environment:
Run the following commands in yourproject's main directory to install new dependencies and runyour web service.If you have not set up a virtual enviornment for local testing, seetesting your web service.
pipinstall-rrequirements.txtpythonmain.pyEnter the following address in your web browser to view your web service:
http://localhost:8080
localhost URLrather than the full IP address of your local host or you will get anauthentication error. This is because your local host's IP address is not listedas an authorized domain in your Firebase project.Deploy your web service
Now that you have authentication working locally, you can re-deploy your webservice to App Engine.
Run the following command from the root directory of your project,where yourapp.yaml file is located:
gcloudappdeployAll traffic is automatically routed to the new version you deployed.
For more information on managing versions,seeManaging Services and Versions.
View your service
To quickly launch your browser and access your web service athttps://PROJECT_ID.REGION_ID.r.appspot.com, run the followingcommand:
gcloudappbrowseNext steps
Now that you've set up user authentication, you're ready to learn how to updateyour web service to personalize data for authenticated users.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.