OAuth2 is an authorization framework that allows third-party applications to gain limited access to an HTTP service on behalf of a user. It also supports delegated authentication using an external Authorization Server such as Google or GitHub.
Key Components of OAuth2
- Resource Owner: The end user who owns the protected data.
- Client (Application): The application requesting access to resources (your Spring Boot app).
- Authorization Server: Authenticates the user and issues access tokens (e.g., Google OAuth2 service).
- Resource Server: Hosts protected resources and validates access tokens.
OAuth2 Flow in Spring Boot
- Client Registration: Register your app with an OAuth2 provider (Google, GitHub) to obtain a client ID and client secret.
- User Authentication: When the user accesses a protected resource, Spring Security redirects them to the provider’s login page.
- Authorization Code Exchange: After successful login, the provider returns an authorization code to your app.
- Access Token Retrieval: The Spring Security OAuth2 client exchanges the code for an access token.
- Access Granted: The token authenticates the user for further requests.
Implementation Steps
Step 1: Create the Spring Boot Project
Use Spring Initializr to create a project:
- Name: spring-boot-oauth2-google
- Language: Java
- Packaging: Jar
- Dependencies: OAuth2 Client, Spring Web, Spring Security, Thymeleaf

Step 2: Add Dependencies
Add the following dependencies into the Spring Boot project.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
</dependencies>
After the project creation done, then the project structure will look like the below image:

Step 3: Configure Application Properties
Rename application.properties to application.yml and configure Google OAuth2:
spring:
security:
oauth2:
client:
registration:
google:
client-id: YOUR_CLIENT_ID
client-secret: YOUR_CLIENT_SECRET
scope: profile, email
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
authorization-grant-type: authorization_code
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/v2/auth
token-uri: https://oauth2.googleapis.com/token
user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
user-name-attribute: sub
server:
port: 8080
- client-id and client-secret: Credentials from your Google developer console.
- scope: Permissions requested (profile and email).
- redirect-uri: URL where Google redirects after login.
Step 4: Configure Spring Security
Create SecurityConfig.java:
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**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login()
.defaultSuccessUrl("/dashboard", true);
}
}
- permitAll(): Allows unauthenticated access to home and login pages.
- authenticated(): Restricts other endpoints.
- oauth2Login(): Enables OAuth2 login via the configured provider.
- defaultSuccessUrl("/dashboard"): Redirects users post-login.
Step 5: Create UserController
UserController.java:
package com.gfg.springbootoauth2google;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class UserController {
@GetMapping("/api/user/info")
public Map<String, Object> userInfo(OAuth2AuthenticationToken authentication) {
return authentication.getPrincipal().getAttributes();
}
}
Purpose: Returns the authenticated user’s information.
Step 6: Create DashboardController
DashboardController.java
package com.gfg.springbootoauth2google;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class DashboardController {
@GetMapping("/dashboard")
public String dashboard(@AuthenticationPrincipal OAuth2User principal, Model model) {
model.addAttribute("username", principal.getAttribute("name"));
model.addAttribute("email", principal.getAttribute("email"));
return "dashboard";
}
}
Purpose: Displays user details on the dashboard page.
Step 7: Main Application Class
This is the entry point of the Spring Boot application.
package com.gfg.springbootoauth2google;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootOauth2GoogleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootOauth2GoogleApplication.class, args);
}
}
This is the main class of the Spring Boot application, where the application is launched using the SpringApplication.run method.
Step 8: Create HTML Views
index.html(src/main/resources/static):
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>Home</title>
<style>
body {
background-color: #e8f5e9; /* Light green background */
font-family: Arial, sans-serif;
color: #2e7d32; /* Dark green text color */
}
h1 {
color: #388e3c; /* Medium green for header */
}
a {
color: #1b5e20; /* Dark green for links */
text-decoration: none;
padding: 10px;
border: 2px solid #1b5e20;
border-radius: 5px;
display: inline-block;
margin-top: 20px;
}
a:hover {
background-color: #a5d6a7; /* Lighter green on hover */
}
</style>
</head>
<body>
<h1>Spring Boot OAuth2</h1>
<!-- Link to initiate OAuth2 login with Google -->
<p><a th:href="@{/oauth2/authorization/google}">Login with Google</a></p>
</body>
</html>
dashboard.html(src/main/resources/templates):
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<style>
body {
background-color: #e8f5e9; /* Light green background */
font-family: Arial, sans-serif;
color: #2e7d32; /* Dark green text color */
}
h1 {
color: #388e3c; /* Medium green for header */
}
p {
margin: 20px 0;
}
</style>
</head>
<body>
<h1>Welcome to Your Dashboard</h1>
<!-- Display the authenticated user's details -->
<p>Username: <span th:text="${username}"></span></p>
<p>Email: <span th:text="${email}"></span></p>
</body>
</html>
Step 9: Run the Application
Run the app using the Maven command:
mvn spring-boot:run

Navigate to http://localhost:8080
Click Login with Google

Select a Google account

Click on the Continue button.

You’ll be redirected to /dashboard, where your name and email are displayed.
