Handling sessions with Firestore Stay organized with collections Save and categorize content based on your preferences.
Many apps needsession managementfor authentication and user preferences.ASP.NET core comes withmiddleware to store sessions in a distributedcache.
ASP.NET's default distributed cache is actually not distributed at all.It stores session data in the memory of the web server. When only one webserver is serving a web site, this strategy is fine. But when manyweb servers are serving a web site, the web site's users can experience errorsand lost data.
To avoid errors and lost data, an ASP.NET app must use a distributedcache that stores data in a persistent data store.This tutorial shows how to manage sessions onCloud Run by storing them in Firestore and encrypting cookies with Cloud Key Management Service.
Objectives
- Deploy the app on Cloud Run.
Costs
In this document, you use the following billable components of Google Cloud:
To generate a cost estimate based on your projected usage, use thepricing calculator.
When you finish the tasks that are described in this document, you can avoid continued billing by deleting the resources that you created. For more information, seeClean up.
Before you begin
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Verify that billing is enabled for your Google Cloud project.
Enable the Firestore, Cloud Run, Cloud Key Management Service, and Cloud Storage APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Verify that billing is enabled for your Google Cloud project.
Enable the Firestore, Cloud Run, Cloud Key Management Service, and Cloud Storage APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.- To create a Firestore database in Native mode, complete the following steps:
- In the Google Cloud console, go to theFirestore viewer page.
Go to the Firestore viewer - From theSelect a Firestore mode screen, clickSelect Native Mode.
- Select alocation for your Firestore database. This location setting is the default Google Cloud resource location for your Google Cloud project. This location is used for Google Cloud services in your Google Cloud project that require a location setting, specifically, your defaultCloud Storage bucket and yourApp Engine app. Warning: After you set the default resource location for your Google Cloud project, you cannot change it.
- ClickCreate Database.
- In the Google Cloud console, go to theFirestore viewer page.
In Cloud Shell, open the app's source code.
Go to Cloud ShellCloud Shell provides command-line access to your Google Cloud resources directly from the browser.
- To download the sample code and change into the app directory, clickProceed.
In Cloud Shell, configure the gcloud CLI to use your new Google Cloud project:
# Configure gcloud for your projectgcloudconfigsetprojectPROJECT_ID
Replace
PROJECT_IDwith the Google Cloud project ID that you created using the Google Cloud console.TheGoogle Cloud CLI is the primary way you interact with your Google Cloud resources from the command line. In this tutorial, you use the gcloud CLI to deploy and monitor your app.
Examining the source code
The following diagram illustrates how Firestore handles sessions for the Cloud Run app.
TheConfigureServices method in theStartup.cs file sets up the app to useCloud KMS for encryption and Cloud Storage to store encrypted keys.
In Cloud Shell, click
to launch the editor and examine theStartup.csfile.publicvoidConfigureServices(IServiceCollectionservices){// Antiforgery tokens require data protection.services.AddDataProtection()// Store keys in Cloud Storage so that multiple instances// of the web application see the same keys..PersistKeysToGoogleCloudStorage(Configuration["DataProtection:Bucket"],Configuration["DataProtection:Object"])// Protect the keys with Google KMS for encryption and fine-// grained access control..ProtectKeysWithGoogleKms(Configuration["DataProtection:KmsKeyName"]);services.AddFirestoreDistributedCache(Configuration["FIRESTORE_PROJECT_ID"]).AddFirestoreDistributedCacheGarbageCollector();services.AddSession();}
Setting up the Google Cloud project
In the Cloud Shell editor, editthe
appsettings.jsonfile and replace the two instances ofYOUR-PROJECT-IDwithyour Google Cloud project ID. Save the file.{"Logging":{"LogLevel":{"Default":"Warning"}},"AllowedHosts":"*","DataProtection":{"Bucket":"YOUR-PROJECT-ID-bucket","Object":"DataProtectionProviderKeys.xml","KmsKeyName":"projects/YOUR-PROJECT-ID/locations/global/keyRings/dataprotectionprovider/cryptoKeys/masterkey"}}Create a new Cloud Key Management Service key ring named
dataprotectionprovider:gcloudkmskeyringscreatedataprotectionprovider--locationglobal
Create a new Cloud Key Management Service key named
masterkey:gcloudkmskeyscreatemasterkey--locationglobal--keyringdataprotectionprovider--purpose=encryptionCreate a Cloud Storage bucket to store the encrypted keys:
gcloudstoragebucketscreategs://PROJECT_ID-bucket
Deploying and running on Cloud Run
You can use theCloud Run to build and deploy an app that runs reliably under heavy load and with largeamounts of data.
This tutorial uses the Cloud Run to deploy the server.
In your Cloud Shell, publish your app:
dotnet publish -c ReleaseUse Cloud Build to build a Docker container and publish to Container Registry:
gcloudbuildssubmit--taggcr.io/PROJECT_ID/sessionsbin/Release/netcoreapp2.1/publish
Run the container with Cloud Run:
gcloudbetarundeploysessions--regionus-central1--platformmanaged--imagegcr.io/PROJECT_ID/sessions--allow-unauthenticated
Make a note of the URL in the output:
Service [sessions] revision [sessions-00003-xiz] has been deployed and is serving100 percent of traffic at https://sessions-r3f3em7nuq-uc.a.run.app
To view the live app, go to the URL that you copied from the previous step.
Deleting sessions
You candelete session data in theGoogle Cloud console or implement an automated deletion strategy. If you use storage solutions for sessions such as Memcache or Redis, expired sessions are automatically deleted.
Debugging the app
If you cannot connect to your Cloud Run app, check the following:
- Check that the
gclouddeploy commands successfully completed and didn'toutput any errors. If there were errors (for example,message=Build failed), fix them, and trydeploying the Cloud Run app again. - See theCloud Run guide to viewing logs.
Clean up
Delete the project
What's next
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.