Firestore でのセッション処理

多くのアプリでは、セッション管理 認証設定とユーザー設定用に必要です。 ASP.NET Core には、セッションを分散キャッシュに保存するためのミドルウェアが付属しています。

ASP.NET のデフォルトの分散キャッシュは実際に配布されることはありません。セッション データはウェブサーバーのメモリに保存されます。ウェブサイトを提供しているウェブサーバーが 1 つだけの場合はこの方法が有効です。しかし、多くのウェブサーバーがウェブサイトを提供している場合、そのウェブサイトのユーザーにはエラーが発生し、データが失われる可能性があります。

エラーとデータの損失を回避するために、ASP.NET アプリは、永続データストアにデータを保存する分散キャッシュを使用する必要があります。 このチュートリアルでは、Cloud Run でセッションを Firestore に保存し、Cloud Key Management Service で Cookie を暗号化してセッションを管理する方法を説明します。

目標

  • アプリを Cloud Run にデプロイする。

費用

このドキュメントでは、課金対象である次のコンポーネントを使用します。 Google Cloud

料金計算ツールを使うと、予想使用量に基づいて費用の見積もりを生成できます。

新規の Google Cloud ユーザーは無料トライアルをご利用いただける場合があります。

このドキュメントに記載されているタスクの完了後、作成したリソースを削除すると、それ以上の請求は発生しません。詳細については、クリーンアップをご覧ください。

始める前に

  1. アカウントにログインします。 Google Cloud を初めて使用する場合は、 アカウントを作成して、実際のシナリオで Google プロダクトのパフォーマンスを評価してください。 Google Cloud新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. 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 the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. 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 the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  8. Firestore データベースをネイティブ モードで作成するには、次の手順に沿って操作してください。
    1. コンソールで、[**Firestore Viewer**] ページに移動します。 Google Cloud
      Firestore Viewer に移動
    2. [Cloud Firestore モードの選択] 画面から、[ネイティブ モードを選択] をクリックします。
    3. Firestore データベースのロケーションを選択します。このロケーション設定は、 プロジェクトのデフォルトの Google Cloud リソースのロケーションです Google Cloud 。 このロケーションは、ロケーション設定を必要とする Google Cloud プロジェクト内の Google Cloud サービス(特にデフォルトのCloud StorageバケットおよびApp Engineアプリ)で使用されます。
    4. [データベースを作成] をクリックします。
  9. Cloud Shell で、アプリのソースコードを開きます。
    Cloud Shell に移動

    Cloud Shell を使用すると、ブラウザからコマンドラインで直接 Google Cloud リソースにアクセスできます。

  10. サンプルコードをダウンロードしてアプリのディレクトリに移動するには、[続行] をクリックします。
  11. Cloud Shell で、gcloud CLI を構成して 新しい Google Cloud プロジェクトを使用します:

    # Configure gcloud for your project
    gcloud config set project PROJECT_ID

    PROJECT_ID は、 Google Cloud コンソールを使用して作成したプロジェクト ID に置き換えます。 Google Cloud

    Google Cloud CLI は、コマンドラインから リソースを操作する基本的な方法です。 Google Cloud このチュートリアルでは、gcloud CLI を使用してアプリをデプロイおよびモニタリング します。

ソースコードを調べる

次の図は、Firestore が Cloud Run アプリのセッションを取り扱う方法を示しています。

アーキテクチャの図: ユーザー、Cloud Run、Firestore。

Startup.cs ファイルの ConfigureServices メソッドは、暗号化に Cloud KMS を使用し、暗号化された鍵を Cloud Storage に保存するようにアプリを設定します。

  1. Cloud Shell で、エディタを立ち上げる をクリックしてエディタを起動し、Startup.cs ファイルを調べます。

    public void ConfigureServices(IServiceCollection services)
    {
        // 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();
    }
    

プロジェクトの Google Cloud 設定

  1. Cloud Shell エディタで、 ファイルappsettings.jsonを編集し、YOUR-PROJECT-IDの 2 つのインスタンスを プロジェクト ID に置き換えます。 Google Cloud ファイルを保存します。

    {
      "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"
      }
    }
    
  2. dataprotectionprovider という名前の新しい Cloud Key Management Service キーリングを作成します。

    gcloud kms keyrings create dataprotectionprovider --location global

  3. masterkey という名前の新しい Cloud Key Management Service 鍵を作成します。

    gcloud kms keys create masterkey --location global --keyring dataprotectionprovider --purpose=encryption

  4. 暗号化された鍵を格納する Cloud Storage バケットを作成します。

    gcloud storage buckets create gs://PROJECT_ID-bucket

Cloud Run でのデプロイと実行

Cloud Run を使用すると、高負荷の元で大量の データを使用して正常に実行されるアプリをビルドしてデプロイできます。

このチュートリアルでは、Cloud Run を使用してサーバーをデプロイします。

  1. Cloud Shell で、アプリを公開します。

    dotnet publish -c Release
    
  2. Cloud Build を使用して Docker コンテナをビルドし、Container Registry に公開します。

    gcloud builds submit --tag gcr.io/PROJECT_ID/sessions bin/Release/netcoreapp2.1/publish

  3. Cloud Run を使用してコンテナを実行します。

    gcloud beta run deploy sessions --region us-central1 --platform managed --image gcr.io/PROJECT_ID/sessions --allow-unauthenticated

    出力の URL をメモしておきます。

    Service [sessions] revision [sessions-00003-xiz] has been deployed and is serving
    100 percent of traffic at https://sessions-r3f3em7nuq-uc.a.run.app
  4. ライブアプリを表示するには、前の手順でメモした URL に移動します。

セッションの削除

コンソールでセッション データを削除するか、自動削除戦略を実装できます。Google Cloud セッションに、Memcache や Redis などのストレージ ソリューションを使用すると、期限切れのセッションが自動的に削除されます。

アプリのデバッグ

Cloud Run アプリに接続できない場合は、次の点を確認してください。

  1. gcloud デプロイ コマンドが正常に終了して、エラーを出力しなかったことを確認します。エラー( message=Build failed など)がある場合は、修正し、 Cloud Run アプリのデプロイを再度行ってください。
  2. ログの表示に関する Cloud Run ガイドをご覧ください。

クリーンアップ

プロジェクトを削除する

  1. コンソールで [**リソースの管理**] ページに移動します。 Google Cloud

    [リソースの管理] に移動

  2. プロジェクト リストで、削除するプロジェクトを選択し、[削除] をクリックします。
  3. ダイアログでプロジェクト ID を入力し、 [Shut down] をクリックしてプロジェクトを削除します。

次のステップ