7-how-to-set-up-oauth2-authentication-in-a-spring-boot-application.html

How to Set Up OAuth2 Authentication in a Spring Boot Application

In the world of web applications, security is paramount. OAuth2 has emerged as a preferred standard for authorization, allowing applications to securely access user data without exposing passwords. This article will guide you through the process of setting up OAuth2 authentication in a Spring Boot application, providing you with detailed steps, code examples, and troubleshooting tips.

What is OAuth2?

OAuth2 (Open Authorization 2.0) is an authorization framework that enables third-party applications to obtain limited access to a web service. It allows users to grant access to their data without sharing their credentials. This is particularly useful for applications that require integration with external services like Google, Facebook, or GitHub.

Key Concepts of OAuth2

  • Authorization Server: The server that authenticates the user and issues access tokens.
  • Resource Server: The server that hosts the user data and validates access tokens.
  • Client: The application that requests access to the user data.
  • Resource Owner: The user who owns the data and can grant access to the client.

Use Cases for OAuth2

  1. Social Login: Allow users to log in using their social media accounts.
  2. API Access: Enable applications to access user data from third-party services.
  3. Mobile Applications: Securely access user data from mobile apps.

Setting Up OAuth2 Authentication in Spring Boot

Prerequisites

Before diving into the implementation, ensure you have the following:

  • Java Development Kit (JDK) 11 or higher
  • Maven or Gradle build tool
  • Basic understanding of Spring Boot and RESTful web services

Step 1: Create a Spring Boot Project

Create a new Spring Boot project using Spring Initializr (https://start.spring.io/) with the following dependencies:

  • Spring Web
  • Spring Security
  • Spring OAuth2 Client

You can also set up your project using the command line:

mvn archetype:generate -DgroupId=com.example -DartifactId=oauth2-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Step 2: Add Dependencies

If you created your project manually, add the necessary dependencies to your pom.xml:

<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-web</artifactId>
</dependency>

Step 3: Configure Application Properties

You need to configure your application.yml (or application.properties) file with the OAuth2 client details. Below is an example configuration for Google as an OAuth2 provider:

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}"
        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

Replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your actual credentials obtained from the Google Developer Console.

Step 4: Create a Security Configuration

Create a security configuration class to handle OAuth2 login:

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();
    }
}

Step 5: Create a Controller

Now, let’s create a simple controller to handle requests:

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 HomeController {

    @GetMapping("/")
    public String home() {
        return "home";
    }

    @GetMapping("/user")
    public String user(@AuthenticationPrincipal OAuth2User principal, Model model) {
        model.addAttribute("name", principal.getAttribute("name"));
        return "user";
    }
}

Step 6: Create Thymeleaf Templates

Create templates for the home and user pages using Thymeleaf:

src/main/resources/templates/home.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Home</title>
</head>
<body>
<h1>Welcome to the OAuth2 Demo</h1>
<a href="/oauth2/authorization/google">Login with Google</a>
</body>
</html>

src/main/resources/templates/user.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User</title>
</head>
<body>
<h1>Hello, <span th:text="${name}">User</span></h1>
<a href="/">Home</a>
</body>
</html>

Step 7: Run Your Application

Now that everything is set up, run your application. Open your browser and go to http://localhost:8080. Click on the "Login with Google" link to initiate the OAuth2 authentication process.

Troubleshooting Tips

  • Redirect URI Mismatch: Ensure the redirect URI configured in your application matches the one registered in your OAuth provider.
  • Client ID/Secret Errors: Double-check your client ID and secret in the application.yml file.
  • Dependencies Issues: Make sure you have the necessary Spring Security and OAuth2 dependencies in your project.

Conclusion

Setting up OAuth2 authentication in a Spring Boot application is a straightforward process that enhances your application's security. By integrating OAuth2, you can offer users a seamless login experience while keeping their credentials safe. With the code examples and steps provided in this article, you're now equipped to implement OAuth2 authentication in your own Spring Boot projects. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.