Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Google OAuth2 Authentication on Backend Services

Tech Nov 6 1

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:

  1. Enable required APIs
  2. Create OAuth credentials
  3. 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)

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.