Step 5: Getting Google Sign-In Token using Postman

πŸŽ₯ YouTube Video: Coming Soon – Subscribe to JavaiOS Channel


Getting Google Sign-In Tokens Using Postman πŸ§ͺ

This comprehensive guide walks through obtaining Google Sign-In tokens (ID token and access token) using Postman for testing and development. Essential for testing OAuth2 flows, API authentication, and backend integration in the AdventureTube microservice architecture.


🎯 Overview

Testing OAuth2 authentication flows requires proper token management and configuration. This guide provides step-by-step instructions for setting up Google OAuth2 authentication in Postman, enabling effective testing of protected endpoints and authentication workflows.


πŸ”§ Step 1: Set Up OAuth 2.0 Credentials in Google Cloud Console

Creating OAuth2 Client Credentials

Before testing with Postman, you need to configure OAuth2 credentials in Google Cloud Console.

πŸ“Œ Google Cloud Console Setup

  1. Navigate to Google Cloud Console: Go to Google Cloud Console
  2. Project Selection: Create a new project or select an existing one for your application
  3. Enable APIs: Navigate to APIs & Services > Library and enable:
    • Google+ API (for user profile information)
    • Google Sign-In API
    • Any additional APIs your application requires
  4. Create Credentials: Go to APIs & Services > Credentials
  5. OAuth Client Setup: Click Create Credentials > OAuth client ID
  6. Application Type: Choose Web application
  7. Configure Redirect URI: Set the authorized redirect URI to:
    https://oauth.pstmn.io/v1/callback
  8. Save Credentials: Copy the Client ID and Client Secret for Postman configuration

Important Security Considerations

Setting Value Purpose
Authorized Redirect URIs https://oauth.pstmn.io/v1/callback Postman’s OAuth2 callback handler
Application Type Web application Enables authorization code flow
Authorized Origins https://oauth.pstmn.io Allows Postman to initiate OAuth flow

πŸ”§ Step 2: Configure OAuth 2.0 in Postman

Setting Up Authentication in Postman

Configure Postman to handle Google OAuth2 authentication flow with the credentials from Google Cloud Console.

πŸ“Œ Authorization Configuration

  1. Open Authorization Tab: In your Postman request, go to the Authorization tab
  2. Set Authentication Type: Set Type to OAuth 2.0
  3. Get New Access Token: Click Get New Access Token and configure:

OAuth2 Configuration Parameters

Parameter Value Description
Token Name GoogleSignInToken Identifier for this token configuration
Grant Type Authorization Code OAuth2 flow type for web applications
Callback URL https://oauth.pstmn.io/v1/callback Postman’s OAuth2 callback handler
Auth URL https://accounts.google.com/o/oauth2/auth Google’s authorization endpoint
Access Token URL https://oauth2.googleapis.com/token Google’s token exchange endpoint
Client ID <your-client-id> From Google Cloud Console
Client Secret <your-client-secret> From Google Cloud Console
Scope openid email profile Permissions requested from user
Client Authentication Send as Basic Auth header How to send client credentials

Advanced Configuration Options

πŸ“Œ Additional OAuth2 Settings

{
  "token_name": "GoogleSignInToken",
  "grant_type": "authorization_code",
  "callback_url": "https://oauth.pstmn.io/v1/callback",
  "auth_url": "https://accounts.google.com/o/oauth2/auth",
  "access_token_url": "https://oauth2.googleapis.com/token",
  "client_id": "{{GOOGLE_CLIENT_ID}}",
  "client_secret": "{{GOOGLE_CLIENT_SECRET}}",
  "scope": "openid email profile",
  "client_authentication": "header",
  "authorize_using_browser": true
}

πŸ“Œ Environment Variables Setup

Store sensitive credentials in Postman environment variables:

{
  "GOOGLE_CLIENT_ID": "123456789-abcdef.apps.googleusercontent.com",
  "GOOGLE_CLIENT_SECRET": "GOCSPX-your-client-secret-here",
  "GOOGLE_REDIRECT_URI": "https://oauth.pstmn.io/v1/callback"
}

πŸ”§ Step 3: Execute OAuth2 Flow and Use Tokens

Obtaining Authentication Tokens

Execute the OAuth2 flow to obtain both access and ID tokens for API testing.

πŸ“Œ Authentication Flow Process

  1. Initialize OAuth Flow: Click Get New Access Token in Postman
  2. Browser Authorization: Postman opens browser for Google sign-in
  3. User Consent: User grants permissions for requested scopes
  4. Token Exchange: Google redirects back to Postman with authorization code
  5. Token Response: Postman exchanges code for access and ID tokens

Token Response Analysis

After successful authentication, Google returns multiple token types:

πŸ“Œ Token Response Structure

{
  "access_token": "ya29.a0AfH6SMC...",
  "expires_in": 3599,
  "refresh_token": "1//04...",
  "scope": "openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
  "token_type": "Bearer",
  "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6..."
}

Token Usage Patterns

Token Type Purpose Usage Expiration
Access Token Google API calls Authorization header for Google services 1 hour (3600 seconds)
ID Token User authentication Verify user identity in your backend 1 hour (3600 seconds)
Refresh Token Token renewal Obtain new access tokens without re-auth Long-lived (varies)

πŸ”§ Step 4: Testing Protected Endpoints

Using ID Token for Backend Authentication

The ID token contains user information and is used to authenticate users in your backend services.

πŸ“Œ ID Token Verification Example

// Example request to your backend API
POST /auth/verify-google-token
Content-Type: application/json

{
  "idToken": "eyJhbGciOiJSUzI1NiIsImtpZCI6...",
  "clientId": "123456789-abcdef.apps.googleusercontent.com"
}

πŸ“Œ Backend Authentication Flow

// Spring Boot controller example
@PostMapping("/auth/verify-google-token")
public ResponseEntity<AuthResponse> verifyGoogleToken(@RequestBody GoogleTokenRequest request) {
    try {
        // Verify ID token with Google
        GoogleIdToken idToken = GoogleIdToken.parse(jsonFactory, request.getIdToken());
        GoogleIdToken.Payload payload = idToken.getPayload();
        
        // Extract user information
        String userId = payload.getSubject();
        String email = payload.getEmail();
        String name = (String) payload.get("name");
        
        // Create or update user in your system
        User user = userService.findOrCreateUser(userId, email, name);
        
        // Generate your application's JWT token
        String jwtToken = jwtService.generateToken(user);
        
        return ResponseEntity.ok(new AuthResponse(jwtToken, user));
        
    } catch (Exception e) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
            .body(new AuthResponse("Invalid token"));
    }
}

Using Access Token for Google API Calls

The access token enables calls to Google APIs on behalf of the authenticated user.

πŸ“Œ Google API Request Examples

// Get user profile information
GET https://www.googleapis.com/oauth2/v2/userinfo
Authorization: Bearer ya29.a0AfH6SMC...

// Response:
{
  "id": "123456789012345678901",
  "email": "user@example.com",
  "verified_email": true,
  "name": "John Doe",
  "given_name": "John",
  "family_name": "Doe",
  "picture": "https://lh3.googleusercontent.com/..."
}

πŸ”§ Advanced Testing Scenarios

Token Refresh Workflow

Test automatic token renewal using refresh tokens for long-running sessions.

πŸ“Œ Refresh Token Request

POST https://oauth2.googleapis.com/token
Content-Type: application/x-www-form-urlencoded

client_id={{GOOGLE_CLIENT_ID}}&
client_secret={{GOOGLE_CLIENT_SECRET}}&
refresh_token={{REFRESH_TOKEN}}&
grant_type=refresh_token

Error Handling and Edge Cases

Test various authentication failure scenarios to ensure robust error handling.

πŸ“Œ Common Test Scenarios

Test Case Setup Expected Result
Expired Token Use token older than 1 hour 401 Unauthorized response
Invalid Token Modify token signature 401 Unauthorized with error details
Wrong Client ID Use mismatched client_id in verification Token validation failure
Revoked Token Revoke token in Google account settings 401 Unauthorized

πŸ› Troubleshooting Common Issues

Authentication Problems and Solutions

🚨 Redirect URI Mismatch

Problem: OAuth flow fails with redirect_uri_mismatch error

Solution:

  • Ensure the callback URL in Postman exactly matches the authorized redirect URI in Google Cloud Console
  • Check for trailing slashes or protocol mismatches (http vs https)
  • Verify the redirect URI is properly URL-encoded if it contains special characters

🚨 Invalid Client ID/Secret

Problem: Authentication fails with invalid_client error

Solution:

  • Double-check that the Client ID and Client Secret are correctly copied from Google Cloud Console
  • Ensure there are no extra spaces or hidden characters
  • Verify the OAuth2 client is enabled and not restricted

🚨 Token Not Received

Problem: Postman doesn’t receive tokens after authorization

Solution:

  • Verify all OAuth2 configuration parameters are correct
  • Check that the scopes are properly formatted and supported
  • Ensure the grant type is set to “Authorization Code”
  • Try enabling “Authorize using browser” option

Debugging Tools and Techniques

πŸ“Œ Network Request Analysis

# Monitor OAuth2 flow with curl
curl -v "https://accounts.google.com/o/oauth2/auth?\
client_id=YOUR_CLIENT_ID&\
redirect_uri=https://oauth.pstmn.io/v1/callback&\
scope=openid%20email%20profile&\
response_type=code&\
state=random_state_string"

πŸ“Œ Token Validation

# Validate ID token structure
echo "YOUR_ID_TOKEN" | cut -d'.' -f2 | base64 -d | jq .

# Check token expiration
curl -s "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=YOUR_ACCESS_TOKEN"

πŸ”’ Security Best Practices

Token Management Security

  • βœ… Secure Storage: Never store tokens in plain text or version control
  • βœ… Environment Variables: Use Postman environment variables for sensitive data
  • βœ… Token Rotation: Implement automatic token refresh before expiration
  • βœ… Scope Limitation: Request only the minimum required scopes
  • βœ… HTTPS Only: Always use HTTPS for OAuth2 flows

Development Environment Security

# Postman environment variables (secure)
{
  "GOOGLE_CLIENT_ID": "{{CLIENT_ID}}",
  "GOOGLE_CLIENT_SECRET": "{{CLIENT_SECRET}}",
  "API_BASE_URL": "https://api.adventuretube.net",
  "AUTH_TOKEN": "{{CURRENT_TOKEN}}"
}

πŸ”§ Integration with AdventureTube Backend

Complete Authentication Flow

Integrate Google OAuth2 tokens with AdventureTube microservice authentication.

πŸ“Œ Registration Flow Test

POST {{API_BASE_URL}}/auth/register
Content-Type: application/json

{
  "email": "strider@adventuretube.net",
  "googleIdToken": "{{ID_TOKEN}}",
  "googleId": "123456789012345678901"
}

πŸ“Œ Login Flow Test

POST {{API_BASE_URL}}/auth/login
Content-Type: application/json

{
  "googleIdToken": "{{ID_TOKEN}}"
}

Protected Resource Access

GET {{API_BASE_URL}}/user/profile
Authorization: Bearer {{JWT_TOKEN}}

βœ… Testing Workflow Checklist

Setup Verification βœ…

  • βœ… Google Cloud project configured with OAuth2 credentials
  • βœ… Authorized redirect URIs include Postman callback URL
  • βœ… Required APIs enabled (Google Sign-In, Google+ API)
  • βœ… Client ID and Secret securely stored in Postman environment

Authentication Testing βœ…

  • βœ… OAuth2 flow completes successfully in Postman
  • βœ… Both access_token and id_token received
  • βœ… Token expiration and refresh workflow tested
  • βœ… Error scenarios validated (expired, invalid tokens)

Backend Integration βœ…

  • βœ… ID token verification working in backend
  • βœ… User registration flow with Google credentials
  • βœ… Protected endpoints accessible with valid tokens
  • βœ… Error handling for authentication failures

Security Validation βœ…

  • βœ… Tokens properly secured in environment variables
  • βœ… HTTPS used for all authentication requests
  • βœ… Minimal required scopes requested
  • βœ… Token rotation and refresh tested

πŸŽ“ Key Takeaways

  1. Proper OAuth2 Setup: Correct configuration in both Google Cloud Console and Postman is essential for successful authentication testing
  2. Token Security: Always use environment variables and secure storage for sensitive authentication credentials
  3. Comprehensive Testing: Test both successful authentication flows and error scenarios to ensure robust application behavior
  4. Backend Integration: Verify that ID tokens are properly validated and used for user authentication in your microservices
  5. Development Workflow: Establish repeatable testing procedures for OAuth2 flows to support continuous development and debugging

Mastering OAuth2 testing with Postman enables efficient development and debugging of authentication flows, ensuring reliable user authentication in the AdventureTube microservice ecosystem.


πŸŽ‰ Congratulations! You’ve Completed Backend Development Fundamentals

🧭 Complete Backend Development Fundamentals Series:

  • ▢️ Backend Development Fundamentals Hub
  • βœ… Step 1: RESTful API Design & Best Practices
  • βœ… Step 2: URI Construction & API Response Patterns
  • βœ… Step 3: Maven Dependency Management
  • βœ… Step 4: Eureka Service Registration & Discovery
  • βœ… Step 5: Testing Tools & Authentication Setup (Completed)

πŸš€ Ready for advanced topics? Explore our Spring Security & Authentication or Spring Documentation series!

Part of the AdventureTube technical blog series supporting the JavaiOS YouTube channel.

Leave a Comment

Your email address will not be published. Required fields are marked *