π§ͺ Step 5: Testing Tools & Authentication Setup
π§ Series Navigation:
- βΆοΈ 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 (Current)
π₯ 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
- Navigate to Google Cloud Console: Go to Google Cloud Console
- Project Selection: Create a new project or select an existing one for your application
- 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
- Create Credentials: Go to APIs & Services > Credentials
- OAuth Client Setup: Click Create Credentials > OAuth client ID
- Application Type: Choose Web application
- Configure Redirect URI: Set the authorized redirect URI to:
https://oauth.pstmn.io/v1/callback
- 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
- Open Authorization Tab: In your Postman request, go to the Authorization tab
- Set Authentication Type: Set Type to
OAuth 2.0
- 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
- Initialize OAuth Flow: Click Get New Access Token in Postman
- Browser Authorization: Postman opens browser for Google sign-in
- User Consent: User grants permissions for requested scopes
- Token Exchange: Google redirects back to Postman with authorization code
- 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
- Proper OAuth2 Setup: Correct configuration in both Google Cloud Console and Postman is essential for successful authentication testing
- Token Security: Always use environment variables and secure storage for sensitive authentication credentials
- Comprehensive Testing: Test both successful authentication flows and error scenarios to ensure robust application behavior
- Backend Integration: Verify that ID tokens are properly validated and used for user authentication in your microservices
- 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.