Ojasa Mirai

Ojasa Mirai

Cloud

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🔧 GCP Account Setup⚙️ GCP Compute Overview🚀 Cloud Run Deployment🎯 App Engine Deployment📁 GCP Storage & Hosting🔥 Firebase Hosting🗄️ Firestore Setup⚡ Firestore Realtime💾 Cloud SQL Setup📊 GCP Monitoring🔑 GCP Authentication📈 GCP Scaling & Performance⚡ Firebase Functions💰 GCP Cost Optimization
Cloud/Gcp Deployment/Gcp Authentication

🔑 GCP Authentication

Introduction

Google Cloud provides multiple authentication and authorization mechanisms: IAM for service accounts, Cloud Identity for user management, and Firebase Authentication for user sign-in. Understanding these is crucial for securing your applications.

Key Learning Outcomes

By the end of this lesson, you'll understand:

  • Service accounts and service account keys
  • Application Default Credentials (ADC)
  • IAM roles and permissions
  • Granting access to resources
  • Best practices for credential management
  • Securely storing secrets

Service Accounts

Create a Service Account

# Create service account
gcloud iam service-accounts create my-app-sa \
  --display-name="My Application Service Account"

# Get service account email
gcloud iam service-accounts list

Create and Manage Keys

# Create key
gcloud iam service-accounts keys create key.json \
  --iam-account=my-app-sa@my-project.iam.gserviceaccount.com

# List keys
gcloud iam service-accounts keys list \
  --iam-account=my-app-sa@my-project.iam.gserviceaccount.com

# Delete old key
gcloud iam service-accounts keys delete KEY_ID \
  --iam-account=my-app-sa@my-project.iam.gserviceaccount.com

Authenticating Applications

Using Service Account Key

Node.js:

const admin = require('firebase-admin');

// Use service account key
const serviceAccount = require('./key.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

const db = admin.firestore();

Python:

import os
from google.oauth2 import service_account

# Load credentials
credentials = service_account.Credentials.from_service_account_file(
    'key.json'
)

# Use credentials
from google.cloud import storage
storage_client = storage.Client(credentials=credentials)

Application Default Credentials (ADC)

Set default credentials:

# Export service account key
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/key.json"

# Or set in code (Python)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/path/to/key.json'

Use ADC automatically:

# ADC automatically finds credentials
from google.cloud import firestore
db = firestore.Client()  # Uses ADC

# Node.js
const admin = require('firebase-admin');
admin.initializeApp();  // Uses ADC

IAM Roles and Permissions

Grant Roles to Service Accounts

# Grant Editor role
gcloud projects add-iam-policy-binding my-project \
  --member=serviceAccount:my-app-sa@my-project.iam.gserviceaccount.com \
  --role=roles/editor

# Grant specific role (Cloud Datastore Editor)
gcloud projects add-iam-policy-binding my-project \
  --member=serviceAccount:my-app-sa@my-project.iam.gserviceaccount.com \
  --role=roles/datastore.editor

# View roles
gcloud projects get-iam-policy my-project

Secret Manager

Store and Retrieve Secrets

# Create secret
echo "db-password-123" | gcloud secrets create db-password \
  --data-file=-

# Grant service account access to secret
gcloud secrets add-iam-policy-binding db-password \
  --member=serviceAccount:my-app-sa@my-project.iam.gserviceaccount.com \
  --role=roles/secretmanager.secretAccessor

# Access secret in code

Node.js:

const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

const client = new SecretManagerServiceClient();

async function getSecret(secretName) {
  const projectId = process.env.GOOGLE_CLOUD_PROJECT;
  const name = client.secretVersionPath(projectId, secretName, 'latest');
  
  const [version] = await client.accessSecretVersion({name});
  return version.payload.data.toString('utf8');
}

// Usage
const dbPassword = await getSecret('db-password');

Python:

from google.cloud import secretmanager

def get_secret(secret_id):
    client = secretmanager.SecretManagerServiceClient()
    project_id = os.environ.get('GOOGLE_CLOUD_PROJECT')
    name = f"projects/{project_id}/secrets/{secret_id}/versions/latest"
    
    response = client.access_secret_version(request={"name": name})
    return response.payload.data.decode('UTF-8')

# Usage
db_password = get_secret('db-password')

Firebase Authentication

Set Up User Sign-In

import { initializeApp } from 'firebase/app';
import { 
  getAuth, 
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  signOut,
  onAuthStateChanged
} from 'firebase/auth';

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

// Sign up
async function signUp(email, password) {
  try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    return userCredential.user;
  } catch (error) {
    console.error('Sign up error:', error);
  }
}

// Sign in
async function signIn(email, password) {
  try {
    const userCredential = await signInWithEmailAndPassword(auth, email, password);
    return userCredential.user;
  } catch (error) {
    console.error('Sign in error:', error);
  }
}

// Listen to auth state
onAuthStateChanged(auth, (user) => {
  if (user) {
    console.log('User logged in:', user.email);
  } else {
    console.log('User logged out');
  }
});

// Sign out
async function logout() {
  await signOut(auth);
}

Best Practices

1. Never Commit Keys

.gitignore:

key.json
.env
.env.local
secrets/

2. Use Environment Variables

.env:

GOOGLE_CLOUD_PROJECT=my-project
GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json
DB_PASSWORD=secret-from-secret-manager
// Load environment variables
require('dotenv').config();

const projectId = process.env.GOOGLE_CLOUD_PROJECT;

3. Rotate Keys Regularly

# List keys
gcloud iam service-accounts keys list \
  --iam-account=my-app-sa@my-project.iam.gserviceaccount.com

# Delete old keys (older than 90 days)
gcloud iam service-accounts keys delete KEY_ID \
  --iam-account=my-app-sa@my-project.iam.gserviceaccount.com

4. Use Least Privilege

# Grant only necessary role
gcloud projects add-iam-policy-binding my-project \
  --member=serviceAccount:my-app-sa@my-project.iam.gserviceaccount.com \
  --role=roles/cloud.run.invoker

Key Takeaways

  • **Service accounts** authenticate applications to GCP
  • **ADC** simplifies credential management
  • **IAM roles** control what resources a service account can access
  • **Secret Manager** securely stores sensitive data
  • **Firebase Authentication** enables user sign-in
  • **Key rotation** improves security

Next Steps

Learn about Cloud Identity for user management, or explore IAM conditions for fine-grained access control.


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn