OAuth

suggest change

OAuth 2.0 is the industry-standard protocol for delegated authorization. It enables third-party applications to access protected HTTP resources on behalf of a user—or on the application's own behalf—without exposing user credentials. Combined with OpenID Connect (OIDC), it provides identity and authentication.

In Java, OAuth 2.0 can be implemented via low-level HTTP clients using standard token endpoints or through enterprise frameworks like Spring Security OAuth2.


1. Core OAuth 2.0 Roles and Flows

Common Flows

  1. Authorization Code Flow with PKCE: Standard for browser-based, mobile, and server-side web applications.
  2. Client Credentials Flow: Standard for machine-to-machine (M2M) server-to-server communication without human user involvement.

2. Machine-to-Machine OAuth (Client Credentials Flow) with Pure Java

For microservices calling protected backend APIs, the client authenticates directly using its client_id and client_secret to obtain a short-lived Bearer token:

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.Map;

public class OAuthClientCredentials {

    private final HttpClient httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

    public record TokenResponse(String accessToken, int expiresIn) {}

    public String fetchAccessToken(String tokenEndpoint, String clientId, String clientSecret, String scope) throws Exception {
        // Form-encoded body
        String formBody = "grant_type=client_credentials"
                + "&scope=" + URLEncoder.encode(scope, StandardCharsets.UTF_8);

        // Basic authentication header: client_id:client_secret
        String credentials = clientId + ":" + clientSecret;
        String encodedAuth = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(tokenEndpoint))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("Authorization", "Basic " + encodedAuth)
                .POST(HttpRequest.BodyPublishers.ofString(formBody))
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

        if (response.statusCode() != 200) {
            throw new IllegalStateException("OAuth token request failed with status " + response.statusCode() + ": " + response.body());
        }

        // Parse access_token from JSON response (using simple substring or Jackson/Gson)
        return extractJsonField(response.body(), "access_token");
    }

    public String callProtectedApi(String apiUrl, String bearerToken) throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(apiUrl))
                .header("Authorization", "Bearer " + bearerToken)
                .header("Accept", "application/json")
                .GET()
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        return response.body();
    }

    private static String extractJsonField(String json, String field) {
        String marker = "\"" + field + "\":\"";
        int start = json.indexOf(marker);
        if (start == -1) throw new IllegalArgumentException("Field not found: " + field);
        start += marker.length();
        int end = json.indexOf("\"", start);
        return json.substring(start, end);
    }
}

3. Protecting APIs with Spring Boot and OAuth2 Resource Server

In modern enterprise architectures, microservices act as OAuth2 Resource Servers that validate incoming JWT access tokens issued by identity providers (like Keycloak or Okta).

Maven Dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Configuration (application.yml)

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          # Automatically retrieves JWKS public keys from the identity provider
          issuer-uri: https://auth.mycompany.com/realms/production

Security Configuration

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public/**").permitAll()
                .requestMatchers("/api/admin/**").hasAuthority("SCOPE_admin")
                .anyRequest().authenticated()
            )
            // Validate incoming Bearer tokens using JWT verification
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));

        return http.build();
    }
}

Accessing Token Claims in Controllers

package com.example.controller;

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.Map;

@RestController
public class UserProfileController {

    @GetMapping("/api/me")
    public Map<String, Object> getUserProfile(@AuthenticationPrincipal Jwt jwt) {
        // Map.of() rejects null values, and optional claims like "email" may be missing
        Map<String, Object> profile = new LinkedHashMap<>();
        profile.put("userId", jwt.getSubject());
        profile.put("email", jwt.getClaimAsString("email"));
        profile.put("scopes", jwt.getClaimAsString("scope")); // space-separated, e.g. "openid email"
        profile.put("issuedAt", jwt.getIssuedAt());
        return profile;
    }
}

4. OAuth2 Client Login in Spring Boot (Social Login)

For user-facing web applications allowing users to log in with GitHub or Google:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
spring:
  security:
    oauth2:
      client:
        registration:
          github:
            client-id: ${GITHUB_CLIENT_ID}
            client-secret: ${GITHUB_CLIENT_SECRET}
            scope: read:user,user:email

Spring Security automatically coordinates the browser redirection, state validation, authorization code exchange, and session establishment.


5. Security Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents