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)});});
請注意,onAuthStateChanged() 方法會儲存使用者的 ID 權杖做為 Cookie,藉此控制使用者登入或登出時的變更內容。這個 ID 權杖是 Firebase 在使用者成功登入時自動產生的專屬權杖,可供伺服器用於驗證使用者。
更新網路服務以使用權杖
接下來,使用專屬的 Firebase ID 憑證在伺服器上驗證使用者,然後對使用者的憑證進行解密,以便將資料列印後回傳給使用者。
如要使用 Firebase ID 憑證:
擷取、驗證並解密位在 main.py 檔案的 root 方法中的憑證。
fromflaskimportFlask,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)
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-06-16 (世界標準時間)。"],[[["The `REGION_ID` is a Google-assigned code based on the region selected during app creation, which is included in App Engine URLs for apps created after February 2020, and is optional for apps created before that date."],["This guide outlines how to add a user sign-in flow to a Python web service using Firebase Authentication, enabling users to authenticate and view their information."],["Firebase provides JavaScript methods and variables to configure sign-in behaviors, including sign-out functionality and a variable for the sign-in UI, managing the visual changes based on user authentication status."],["The process includes retrieving, verifying, and decrypting a unique Firebase ID token on the server side, using this token to authenticate users and access their data."],["After local testing with Firebase, you can redeploy the web service to App Engine, making the updated version live, and then use the gcloud app browse command to view it."]]],[]]