Spring Boot Backend Development Course, Implementing Login and Logout with OAuth2, Testing OAuth2 Execution

In today’s web applications, authentication and authorization are crucial elements, and OAuth2 is a widely used standard for implementing them. In this course, we will explore in detail how to implement OAuth2-based login and logout functionality using Spring Boot. The goal of this course is to apply a secure authentication method through OAuth2 in a Spring Boot application and learn how to test it.

1. What is OAuth2?

OAuth2 (Open Authorization 2.0) is an authorization framework that allows internet users to use their accounts with other services without exposing their information to third-party applications. Essentially, OAuth2 operates based on access tokens, which allow users to access their data. During this process, there is no need to share the user’s password.

1.1 Components of OAuth2

  • Resource Owner: The owner of the resource, usually the user.
  • Client: The application that requests the service on behalf of the resource owner.
  • Authorization Server: The server that authenticates the client’s request and issues an access token after consent.
  • Resource Server: The server that can access the protected resources (e.g., user data).

1.2 OAuth2 Flow

The authentication flow of OAuth2 proceeds as follows:

  1. The user sends an authentication request to the Authorization Server through the client.
  2. If the user successfully authenticates, the Authorization Server issues an access token to the client.
  3. The client sends the issued access token to the Resource Server to access the protected resources.

2. Setting up Spring Boot Environment

To set up the Spring Boot environment, we first need to add the necessary dependencies. To do this, we will use Spring Initializr to create a project.

2.1 Creating a Project in Spring Initializr

Create a Spring Boot project with the following settings:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.6.3 (select the latest version)
  • Dependencies: Spring Web, Spring Security, Spring Data JPA, H2 Database

2.2 Modifying the pom.xml File

Next, add the OAuth2-related dependencies to the pom.xml file:

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

3. OAuth2 Configuration

To configure OAuth2, modify the application.yml file to include the Authorization Server and Resource Server information.

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
            user-name-attribute: sub

4. Spring Security Configuration

Configure Spring Security to handle authentication and authorization. Below is an example of a basic security configuration class:

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;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/login").permitAll()
                .anyRequest().authenticated()
                .and()
            .oauth2Login();
    }
}

5. Retrieving User Information

Once the user successfully authenticates, retrieve user information through the OAuth2 client. To do this, create a controller.

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @GetMapping("/user")
    public OAuth2User getUser(@AuthenticationPrincipal OAuth2User principal) {
        return principal;
    }
}

6. Testing and Running

Run the application and access http://localhost:8080 in your web browser. The user will be redirected to the Google login page by clicking the login button. After logging in, they can check their user information via the /user endpoint.

Conclusion

In this course, we explored how to implement login and logout functionality using OAuth2 with Spring Boot. Throughout this process, we learned the basic concepts of OAuth2, setting up the required dependencies, configuring Spring Security, and retrieving user information. This allows you to add a more secure login feature to your web applications.

References