טיפול בסשנים באמצעות Firestore

באפליקציות רבות נדרש ניהול סשנים לצורך אימות והעדפות משתמש. ‫ASP.NET Core כולל תוכנת ביניים לאחסון סשנים במטמון מבוזר.

מטמון מבוזר שמוגדר כברירת מחדל ב-ASP.NET הוא למעשה לא מבוזר בכלל. הוא מאחסן את נתוני הסשן בזיכרון של שרת האינטרנט. האסטרטגיה הזו מתאימה אם רק שרת אינטרנט אחד מציג אתר. אבל כששרתי אינטרנט רבים מציגים אתר אינטרנט, משתמשי האתר עלולים להיתקל בשגיאות ולאבד נתונים.

כדי למנוע שגיאות ואובדן נתונים, אפליקציית ASP.NET צריכה להשתמש במטמון מבוזר שמאחסן נתונים במאגר נתונים קבוע. במדריך הזה נסביר איך לנהל סשנים ב-Cloud Run באמצעות אחסון שלהם ב-Firestore והצפנה של קובצי Cookie באמצעות Cloud Key Management Service.

מטרות

  • פורסים את האפליקציה ב-Cloud Run.

עלויות

במסמך הזה משתמשים ברכיבים הבאים של Cloud de Confiance by S3NS, והשימוש בהם כרוך בתשלום:

כשמסיימים את המשימות שמתוארות במסמך הזה אפשר למחוק את המשאבים שיצרתם כדי להימנע מחיובים נוספים. מידע נוסף זמין בקטע הסרת המשאבים.

לפני שמתחילים

  1. In the Cloud de Confiance console, on the project selector page, select or create a Cloud de Confiance 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

  2. Verify that billing is enabled for your Cloud de Confiance project.

  3. 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

  4. כדי ליצור מסד נתונים של Firestore במצב Native, פועלים לפי השלבים הבאים:
    1. נכנסים לדף Firestore viewer במסוף Cloud de Confiance .
      כניסה לכלי לצפייה ב-Firestore
    2. במסך Select a Firestore mode (בחירת מצב Firestore), לוחצים על Select Native Mode (בחירת מצב מקורי).
    3. בוחרים מיקום למסד הנתונים של Firestore. הגדרת המיקום הזו היא מיקום ברירת המחדל Cloud de Confiance של משאבים בפרויקט Cloud de Confiance . המיקום הזה משמש את Cloud de Confiance השירותים בפרויקט Cloud de Confiance שדורשים הגדרת מיקום, במיוחד את קטגוריית ברירת המחדל של Cloud Storage ואת אפליקציית App Engine.
    4. לוחצים על יצירת מסד נתונים.
  5. ב-Cloud Shell, פותחים את קוד המקור של האפליקציה.
    כניסה ל-Cloud Shell

    ‫Cloud Shell נותנת גישה למשאבים שלכם ב-Google Cloud בממשק שורת פקודה ישירות מהדפדפן. Cloud de Confiance

  6. כדי להוריד את הקוד לדוגמה ולעבור לספריית האפליקציה, לוחצים על המשך.
  7. ב-Cloud Shell, מגדירים את ה-CLI של gcloud לשימוש בפרויקט החדש Cloud de Confiance :

    # Configure gcloud for your project
    gcloud config set project PROJECT_ID

    מחליפים את PROJECT_ID במזהה הפרויקט שיצרתם באמצעות מסוף Cloud de Confiance . Cloud de Confiance

    Google Cloud CLI היא הדרך העיקרית לאינטראקציה עם משאבי Cloud de Confiance משורת הפקודה. במדריך הזה משתמשים ב-CLI של gcloud כדי לפרוס את האפליקציה ולעקוב אחריה.

בדיקת קוד המקור

בתרשים הבא מוצג אופן הטיפול של Firestore בסשנים באפליקציית Cloud Run.

תרשים של הארכיטקטורה: משתמש, Cloud Run, ‏ Firestore.

השיטה ConfigureServices בקובץ Startup.cs מגדירה את האפליקציה לשימוש ב-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();
    }
    

הגדרת Cloud de Confiance הפרויקט

  1. בעורך של Cloud Shell, עורכים את הקובץ appsettings.json ומחליפים את שני המקרים של YOUR-PROJECT-ID במזהה הפרויקט Cloud de Confiance . שומרים את הקובץ.

    {
      "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. יוצרים אוסף מפתחות חדש ב-Cloud Key Management Service בשם dataprotectionprovider:

    gcloud kms keyrings create dataprotectionprovider --location global

  3. יוצרים מפתח חדש ב-Cloud Key Management Service בשם masterkey:

    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 שהעתקתם מהשלב הקודם.

מחיקת סשנים

אתם יכולים למחוק נתוני סשן במסוףCloud de Confiance או להטמיע אסטרטגיה למחיקה אוטומטית. אם אתם משתמשים בפתרונות אחסון לסשנים כמו Memcache או Redis, סשנים שתוקפם פג נמחקים אוטומטית.

ניפוי באגים באפליקציה

אם אתם לא מצליחים להתחבר לאפליקציית Cloud Run, כדאי לבדוק את הדברים הבאים:

  1. בודקים שהפקודות gcloud deploy הושלמו בהצלחה ולא הוחזרו שגיאות. אם היו שגיאות (לדוגמה, message=Build failed), תקנו אותן ונסו לפרוס את אפליקציית Cloud Run שוב.
  2. אפשר לעיין במדריך של Cloud Run לצפייה ביומנים.

הסרת המשאבים

מחיקת הפרויקט

  1. במסוף Cloud de Confiance , נכנסים לדף Manage resources.

    כניסה לדף Manage resources

  2. ברשימת הפרויקטים, בוחרים את הפרויקט שרוצים למחוק ולוחצים על Delete.
  3. כדי למחוק את הפרויקט, כותבים את מזהה הפרויקט בתיבת הדו-שיח ולוחצים על Shut down.

המאמרים הבאים