Implementing Google OAuth2 Authentication on Backend Services
Overview
Google OAuth2 can be integrated into backend applications without requiring a Google developer account. This guide covers two authentication flows suitable for server-side implementation.
Prereuqisites
Obtaining Credentials
Navigate to the Google Cloud Console Dashboard to:
- Enable required APIs
- Create OAuth credentials
- Configure redirect URIs and other credential parameters
Required Dependencies
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>1.19.0</version>
</dependency>
Authentication Methods
Method 1: Access Token Flow
Obtaining the Access Token
Redirect users to the authorization endpoint:
https://accounts.google.com/o/oauth2/v2/auth?
client_id=YOUR_CLIENT_ID
&redirect_uri=YOUR_REDIRECT_URI
&scope=email openid https://www.googleapis.com/auth/userinfo.email
&response_type=token
After authorization, the callback URL contains the access token:
http://localhost:3000/auth/callback#access_token=ya29.a0AcM612z4i...
Extract the access token from the fragment identifier.
Retrieving User Information
GET https://www.googleapis.com/oauth2/v2/userinfo
Headers:
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/x-www-form-urlencoded
Response:
{
"id": "1000000222211",
"email": "user@gmail.com",
"verified_email": true,
"picture": "https://lh3.googleusercontent.com/..."
}
Validation
The userinfo endpoint returns verified user data. No additional JWT verification is required for this flow.
Method 2: ID Token Flow
Step 1: Obtain Authorization Code
Redirect users to:
https://accounts.google.com/o/oauth2/v2/auth?
client_id=YOUR_CLIENT_ID
&redirect_uri=YOUR_REDIRECT_URI
&scope=email openid https://www.googleapis.com/auth/userinfo.email
&response_type=code
The callback URL contains the authorization code:
http://localhost:3000/auth/callback?code=4%2F0AQlEd8zQ-sWf...
URL decode the code parameter before use.
Step 2: Exchange Code for ID Token
POST https://oauth2.googleapis.com/token
Content-Type: application/x-www-form-urlencoded
code=AUTHORIZATION_CODE
client_id=YOUR_CLIENT_ID
client_secret=YOUR_CLIENT_SECRET
redirect_uri=YOUR_REDIRECT_URI
grant_type=authorization_code
Important: Authorization codes can only be used once.
Response:
{
"access_token": "ya29.a0AcM612xU1YjjT5IOBi4GUTNaMAEXQ...",
"expires_in": 3558,
"token_type": "Bearer",
"id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6..."
}
Step 3: Server-Side Token Verification
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import org.springframework.stereotype.Service;
import java.util.Collections;
@Service
public class GoogleAuthenticationService {
private static final String AUDIENCE = "YOUR_CLIENT_ID.apps.googleusercontent.com";
private final GoogleIdTokenVerifier tokenVerifier;
public GoogleAuthenticationService() throws Exception {
this.tokenVerifier = new GoogleIdTokenVerifier.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
GsonFactory.getDefaultInstance()
)
.setAudience(Collections.singletonList(AUDIENCE))
.build();
}
public boolean validateCredentials(String email, String idTokenString) {
try {
GoogleIdToken idToken = tokenVerifier.verify(idTokenString);
if (idToken == null) {
return false;
}
GoogleIdToken.Payload payload = idToken.getPayload();
String tokenEmail = payload.getEmail();
return email != null && email.equals(tokenEmail);
} catch (Exception ex) {
return false;
}
}
}
Choosing a Method
| Aspect | Access Token | ID Token |
|---|---|---|
| Endpoint | userinfo | oauth2.googleapis.com/token |
| Validation | None required | JWT signature verification |
| Use Case | Simple authentication | Secure token-based auth |
| Tokan Lifetime | 1 hour | 1 hour (same as access token) |