Skip to content
Rishan Solutions
Rishan Solutions
  • PowerApps
  • SharePoint online
    • Uncategorized
    • Uncategorized
  • PowerAutomate
Rishan Solutions
Latest Posts
  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025 June 24, 2025
  • Recursive Queries in T-SQL May 7, 2025
  • Generating Test Data with CROSS JOIN May 7, 2025
  • Working with Hierarchical Data May 7, 2025
  • Using TRY_CAST vs CAST May 7, 2025
  • Dynamic SQL Execution with sp_executesql May 7, 2025

Implementing OAuth2 in Java Applications

Posted on March 20, 2025March 24, 2025 by Rishan Solutions

Loading

OAuth2 is an authorization framework that allows applications to securely access resources on behalf of a user without exposing their credentials. It is commonly used for Single Sign-On (SSO) and for granting third-party applications access to a user’s resources in a secure and controlled manner.

In Java applications, implementing OAuth2 typically involves using libraries like Spring Security (for Spring-based applications) or integrating with OAuth2 providers such as Google, Facebook, or GitHub.

This guide will walk you through implementing OAuth2 in a Java application, particularly in Spring Boot, which provides robust support for OAuth2 authentication and authorization.


1. OAuth2 Terminology

Before diving into the implementation, it’s essential to understand key concepts in OAuth2:

  • Resource Owner: The user who owns the resource (e.g., their profile, contacts).
  • Client: The application requesting access to the user’s resources.
  • Authorization Server: The server that authenticates the user and issues access tokens.
  • Resource Server: The server that hosts the protected resources.
  • Access Token: A token that grants access to the resource server.
  • Refresh Token: A token used to obtain a new access token when the old one expires.

2. OAuth2 Authorization Flow

OAuth2 follows different flows depending on the type of client:

  • Authorization Code Grant: Used by web applications where the client can securely store the client secret.
  • Implicit Grant: Used for client-side applications (e.g., JavaScript apps) where the client secret cannot be securely stored.
  • Client Credentials Grant: Used for server-to-server communication where the client acts as its own resource owner.
  • Resource Owner Password Credentials Grant: Used when the user trusts the client application with their username and password.

For most web applications, Authorization Code Grant is the preferred flow.


3. Implementing OAuth2 in a Spring Boot Application

Spring Boot provides a powerful and flexible way to integrate OAuth2 authentication and authorization. The following steps outline how to set up OAuth2 in a Spring Boot application.

Step 1: Add Dependencies

In your pom.xml, add the necessary dependencies for Spring Security OAuth2:

<dependencies>
    <!-- Spring Boot starter for OAuth2 client -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
    
    <!-- Spring Boot starter for web applications (optional, if using web features) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- Spring Boot starter for security (OAuth2 support) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
</dependencies>
  • spring-boot-starter-oauth2-client: Provides integration with OAuth2 for client-side applications.
  • spring-boot-starter-security: Provides the security infrastructure needed to support OAuth2 login.
  • spring-boot-starter-web: Optional if you’re building a web application.

Step 2: Configure OAuth2 in application.properties or application.yml

Spring Boot makes it easy to configure OAuth2 by specifying the OAuth2 provider details in the application.properties file.

Example configuration (application.properties):

# OAuth2 Client Configuration
spring.security.oauth2.client.registration.google.client-id=YOUR_GOOGLE_CLIENT_ID
spring.security.oauth2.client.registration.google.client-secret=YOUR_GOOGLE_CLIENT_SECRET
spring.security.oauth2.client.registration.google.scope=profile,email
spring.security.oauth2.client.registration.google.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.google.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}

spring.security.oauth2.client.provider.google.authorization-uri=https://accounts.google.com/o/oauth2/auth
spring.security.oauth2.client.provider.google.token-uri=https://oauth2.googleapis.com/token
spring.security.oauth2.client.provider.google.user-info-uri=https://www.googleapis.com/oauth2/v3/userinfo

# Define the application’s login page if needed
spring.security.oauth2.client.login-page=/login

In this example, OAuth2 is configured to use Google as the OAuth2 provider:

  • client-id: The client ID provided by the OAuth2 provider (Google in this case).
  • client-secret: The client secret provided by the OAuth2 provider.
  • scope: The scopes for which the application is requesting access (e.g., profile and email).
  • authorization-uri: The URL for the OAuth2 authorization server to start the login process.
  • token-uri: The URL used to exchange the authorization code for an access token.
  • user-info-uri: The URL used to fetch the user’s profile after authentication.

Note: Replace YOUR_GOOGLE_CLIENT_ID and YOUR_GOOGLE_CLIENT_SECRET with your actual Google credentials, which you can obtain by creating an OAuth2 app in the Google Developer Console.

Step 3: Create the Security Configuration Class

Spring Security automatically handles the OAuth2 authentication flow, but you may want to configure it further or add custom behavior.

Here’s a simple configuration class:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/login", "/home").permitAll()  // Public endpoints
                .anyRequest().authenticated()  // Require authentication for other requests
            .and()
            .oauth2Login()  // Enable OAuth2 login
            .defaultSuccessUrl("/dashboard", true)  // Redirect to /dashboard after successful login
            .failureUrl("/login?error");  // Redirect to login page on failure
    }
}
  • oauth2Login(): Enables OAuth2 login. After successful login, the user will be redirected to the /dashboard endpoint.

Step 4: Create a Controller

You can create a simple controller to handle the application’s routes and provide endpoints for users to interact with.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/home")
    public String home() {
        return "home";  // Return the home view for the unauthenticated user
    }

    @GetMapping("/dashboard")
    public String dashboard() {
        return "dashboard";  // Return the dashboard view for authenticated users
    }
}
  • /home: Public route.
  • /dashboard: Protected route, accessible only after successful OAuth2 login.

Step 5: Add Views for the Application

Spring Boot can automatically render views if you’re using a template engine like Thymeleaf or FreeMarker. Here’s an example with Thymeleaf templates.

Example home.html (Home page for unauthenticated users):

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>Welcome to the OAuth2 Demo!</h1>
    <a href="/login">Login with Google</a>
</body>
</html>

Example dashboard.html (Dashboard for authenticated users):

<!DOCTYPE html>
<html>
<head>
    <title>Dashboard</title>
</head>
<body>
    <h1>Welcome to your dashboard!</h1>
    <p>You are logged in as: <span th:text="${#authentication.name}"></span></p>
    <a href="/logout">Logout</a>
</body>
</html>

4. Testing the OAuth2 Flow

  1. Run your Spring Boot application.
  2. Visit the home page (/home), which will display a login button for users to authenticate using Google OAuth2.
  3. After successful authentication via Google, the user will be redirected to the /dashboard page.

5. Handling Token Refresh (Optional)

If your OAuth2 provider supports refresh tokens (e.g., Google), you can implement token refresh logic using the OAuth2AuthorizedClientService to refresh the access token when it expires.

Example of refreshing an access token:

import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;

public class TokenService {

    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;

    public OAuth2AccessToken refreshAccessToken(String clientRegistrationId) {
        OAuth2AuthorizedClient authorizedClient = 
            authorizedClientService.loadAuthorizedClient(clientRegistrationId, "user");

        // Refresh access token using OAuth2 provider's API
        // (This process depends on the OAuth2 provider and their token refresh endpoints)
        return authorizedClient.getAccessToken();
    }
}

Posted Under JavaAuthorization Code Grant Google OAuth2 Java OAuth2 OAuth2 Authentication OAuth2 Login Secure Login Single Sign-On Spring Boot Spring Security Spring Security OAuth2 Token-Based Authentication

Post navigation

Java SSL/TLS Implementation and Certificates
Implementing JWT (JSON Web Token) in Java

Leave a Reply Cancel reply

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

Recent Posts

  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025
  • Recursive Queries in T-SQL
  • Generating Test Data with CROSS JOIN
  • Working with Hierarchical Data
  • Using TRY_CAST vs CAST

Recent Comments

  1. Michael Francis on Search , Filter and Lookup in power apps
  2. A WordPress Commenter on Hello world!

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • March 2024
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • June 2023
  • May 2023
  • April 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • January 2022

Categories

  • Active Directory
  • AI
  • AngularJS
  • Blockchain
  • Button
  • Buttons
  • Choice Column
  • Cloud
  • Cloud Computing
  • Data Science
  • Distribution List
  • DotNet
  • Dynamics365
  • Excel Desktop
  • Extended Reality (XR) – AR, VR, MR
  • Gallery
  • Icons
  • IoT
  • Java
  • Java Script
  • jQuery
  • Microsoft Teams
  • ML
  • MS Excel
  • MS Office 365
  • MS Word
  • Office 365
  • Outlook
  • PDF File
  • PNP PowerShell
  • Power BI
  • Power Pages
  • Power Platform
  • Power Virtual Agent
  • PowerApps
  • PowerAutomate
  • PowerPoint Desktop
  • PVA
  • Python
  • Quantum Computing
  • Radio button
  • ReactJS
  • Security Groups
  • SharePoint Document library
  • SharePoint online
  • SharePoint onpremise
  • SQL
  • SQL Server
  • Template
  • Uncategorized
  • Variable
  • Visio
  • Visual Studio code
  • Windows
© Rishan Solutions 2025 | Designed by PixaHive.com.
  • Rishan Solutions