Open In App

Spring Boot - OAuth2 Authentication and Authorization

Last Updated : 04 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

OAuth2 is a widely-used protocol for authorization that enables applications to securely access resources on behalf of users. When combined with Spring Boot, OAuth2 facilitates authentication and authorization for both REST APIs and web applications. This article will walk you through setting up OAuth2 in a Spring Boot application.

OAuth2 in Spring Boot

OAuth2 is an authorization framework that allows third-party applications to gain limited access to an HTTP service on behalf of a user. It can also handle authentication by delegating it to a third-party service, known as the Authorization Server.

Key Components of OAuth2

  • Resource Owner: The end user who owns the data the client application wants to access.
  • Client (Application): The application requesting access to the resource. In Spring Boot, this is your application.
  • Authorization Server: Authenticates the user and issues an access token to the client. Examples include Google's OAuth2 service.
  • Resource Server: Hosts the protected resources and verifies the access token provided by the client.

How OAuth2 Works in Spring Boot

In a Spring Boot application, OAuth2 can be integrated to handle both authentication and authorization. The framework relies on Spring Security, which provides robust mechanisms for securing applications.

Here’s how OAuth2 fits into the Spring Boot architecture:

  1. Client Registration: You need to register the application with the OAuth2 provider (e.g., Google, GitHub) to obtain a client ID and client secret. These credentials are used to identify the application to the authorization server.
  2. OAuth2 Client Setup in Spring Boot: In Spring Boot, configure the OAuth2 client settings in the application.properties or application.yml file. This includes specifying the client ID, client secret, authorization server URLs, and scopes of access. The Spring Security OAuth2 client automatically handles the redirection to the authorization server and manages the exchange of authorization codes for access tokens.
  3. Authentication Flow:
    • When a user tries to access a secured resource, Spring Security intercepts the request and checks if the user is authenticated.
    • If the user is not authenticated, Spring Security redirects them to the OAuth2 provider's login page.
    • After successful authentication, the OAuth2 provider redirects the user back to the application with an authorization code.
    • The Spring Security OAuth2 client exchanges this code for an access token, which is then used to authenticate the user within the application.

Implementation of OAuth2 Authentication and Authorization

Step 1: Create the Spring Boot Project

Create a new Spring Boot project with the following options:

  • Name: spring-boot-oauth2-google
  • Language: Java
  • Type: Maven
  • Packaging: Jar

Click on the Next button.

Project Metadata

Step 2: Add Dependencies

Add the following dependencies into the Spring Boot project.

Project Metadata

Project Structure

After the project creation done, then the project structure will look like the below image:

Project Structure

Step 3: Configure Application Properties

Rename the application.properties file to application.yml and add the following Google OAuth2 configuration:

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
client-name: Google
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/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 are your Google OAuth credentials.
  • scope specifies the data you are requesting from Google.
  • redirect-uri is where Google will send the user after successful authentication.

Step 4: Create the SecurityConfig Class

Create the SecurityConfig class to set up the security rules for the application.

SecurityConfig.java:

Java
import org.springframework.context.annotation.Bean;
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;
import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/login**").permitAll()  // Allow unauthenticated access to home and login pages
                .anyRequest().authenticated()  // Require authentication for all other requests
                .and()
            .oauth2Login()  // Enable OAuth2 login
                .defaultSuccessUrl("/dashboard", true);  // Redirect to dashboard after successful login
    }
}
  • antMatchers("/", "/login**").permitAll(): Allows unauthenticated access to the home and login pages. This ensures that users can access these pages without logging in.
  • anyRequest().authenticated(): Requires authentication for all other requests, ensuring that users need to be logged in to access other parts of the application.
  • oauth2Login(): Configures the application to use OAuth2 login.
  • defaultSuccessUrl("/dashboard", true): Redirects users to the dashboard page after a successful login.

Step 5: Create the UserController Class

This controller class handles requests for secured resources. Once authenticated, users will be able to access this resource.

UserController.java:

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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @GetMapping("/info")
    public Map<String, Object> userInfo(OAuth2AuthenticationToken authentication) {
        // Return the user's attributes as a map
        return authentication.getPrincipal().getAttributes();
    }
}

This class defines an endpoint that returns the authenticated user's information as a map of attributes. It uses Spring Security's OAuth2AuthenticationToken to access the user's details.

Step 6: Create the DashboardController Class

This controller class handles requests to the /dashboard endpoint and passes the user information to the view.

DashboardController.java

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) {
        // Extract user details from OAuth2User
        String username = principal.getAttribute("name");
        String email = principal.getAttribute("email");

        // Add user details to the model
        model.addAttribute("username", username);
        model.addAttribute("email", email);

        // Return the dashboard view
        return "dashboard";
    }
}

This class handles requests to the /dashboard endpoint, extracting user information from the OAuth2 token and adding it to the model. The view then displays this information on the dashboard page.

Step 7: Main Class

No changes are required in the main class. This is the entry point of the Spring Boot application.

Java
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) {
        // Start the Spring Boot application
        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 the index.html File

Create a simple index.html file in the src/main/resources/static directory. This will provide a link for the user to log in.

index.html

HTML
<!DOCTYPE html>
<html xmlns:th="http://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>

This HTML file provides a simple home page with a link to initiate the OAuth2 login process using Google. The styling gives it a clean, green-themed appearance.

Step 9: Create the dashboard.html File

Create a dashboard.html file in the src/main/resources/templates directory to display user information after a successful login.

dashboard.html

HTML
<!DOCTYPE html>
<html xmlns:th="http://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>

This HTML file represents the dashboard page that displays the authenticated user's username and email. The page is styled similarly to the home page, maintaining a consistent look and feel.

pom.xml file:

XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gfg</groupId>
    <artifactId>spring-boot-oauth2-google</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-oauth2-google</name>
    <description>spring-boot-oauth2-google</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
    </properties>
    <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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Step 10: Running the Application

Once all the configurations are done, you can run the application by using the following Maven command:

mvn spring-boot:run

Output:

Application Started

Step 12: Test the Application

Access the application by navigating to http://localhost:8080 in your browser. You will be prompted to log in with Google.

http://localhost:8080

Output:

Home Page


Click on the "Login with Google" link. Choose the google account to login with application.

Choose Google account


Click on the Continue button.

Click Continue


After successful login, we will be redirected to the /dashboard page, where you will see the username and email displayed in the dashboard page.

Dashboard


This example project demonstrates how to use the OAuth2 Authentication and Authorization in the Spring Boot application.


Next Article

Similar Reads