Spring Boot Backend Development Course, Implementing Login and Logout with OAuth2, Resolving Test Code Failures and Modifying Code

Implementing Login/Logout with OAuth2

Spring Boot is a Java-based web application development framework that provides powerful and flexible features.
In this tutorial, we will learn how to implement secure login and logout functionality using OAuth2.
OAuth2 is a protocol that allows client applications to safely access data from resource servers.
This allows for complete user authentication management.

1. Project Setup

Use Spring Initializr (https://start.spring.io/) to create a new project.
The necessary dependencies are as follows:

  • Spring Web
  • Spring Security
  • OAuth2 Client
  • Spring Data JPA
  • H2 Database (for testing)

Check the build.gradle or pom.xml file of the generated project using Maven or Gradle to ensure it is set up correctly.

2. OAuth2 Configuration

Add OAuth2 client configuration to the application.yml file.
For example, if using Google OAuth2, you can set it up as follows:

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

3. Security Configurations

Configure security by extending the WebSecurityConfigurerAdapter class.
You can set up how to handle the login page and results.

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("/", "/oauth2/**", "/login**").permitAll()
                .anyRequest().authenticated()
                .and()
            .oauth2Login()
                .loginPage("/login")
                .defaultSuccessUrl("/", true);

        // Logout configuration
        http.logout()
            .logoutSuccessUrl("/")
            .permitAll();
    }
}

4. Login and Logout Handling Controller

Next, implement a Controller to handle login and logout requests.
Below is an example of a basic Controller:

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

@Controller
public class LoginController {
    
    @GetMapping("/login")
    public String login() {
        return "login"; // Return to login.html
    }
}

5. Implementing Login & Logout Pages

Implement the login page using Thymeleaf or JSP.
Below is an example using Thymeleaf:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Login</title>
</head>
<body>
    <h1>Login Page</h1>
    <a href="@{/oauth2/authorization/google}">Login with Google</a>
</body>
</html>

Resolving Test Code Failures and Modifying Code

After implementing OAuth2 login handling, you need to write test code to confirm that the functionality works correctly.
However, the initially written tests may fail. This section explains how to identify and correct the reasons for failure.

1. Writing Test Code

Write code to test OAuth2 login using Spring Test. Below is an example of basic test code:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest
@AutoConfigureMockMvc
public class LoginControllerTest {
    
    @Autowired
    private MockMvc mockMvc;

    @Test
    @WithMockUser
    public void testLoginPage() throws Exception {
        mockMvc.perform(get("/login"))
            .andExpect(status().isOk());
    }
}

2. Analyzing Causes of Failure

If the tests fail, there may be various reasons for this.
The most common issues are authentication or path configuration problems. For instance, the URL for the login page may be incorrectly specified or
set to prevent access for unauthenticated users, causing the failure.

3. Example of Code Modification

If the test expects a login page but the page does not exist, you need to modify the login page path.
You may need to revise the Controller as follows.

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

@Controller
public class LoginController {
    
    @GetMapping("/login")
    public String login() {
        return "login"; // Return to login.html
    }
}

4. Rerun Tests

After modifying the code, rerun the tests to check if they succeed.

Conclusion

In this tutorial, we learned how to implement login/logout functionality using OAuth2 with Spring Boot, as well as how to write and modify test code.
OAuth2 is a critical element in modern web applications and helps to enhance security.
Additionally, writing test code to verify that functionality works correctly is a very important process in software development.
This allows us to develop stable and secure applications.

Spring Boot Backend Development Course, Implementing Login and Logout with OAuth2, What are Cookies

1. Introduction

The importance of user authentication and authorization management in modern web application development is increasing day by day. For this reason, the OAuth2 protocol is widely used, providing a way to handle user authentication more flexibly across various systems and platforms. In this course, we will explore how to implement login and logout functionalities based on OAuth2 using Spring Boot and the concept of cookies in detail.

2. What is Spring Boot?

Spring Boot is a development framework based on the Spring framework, designed to support rapid development and simplify complex configurations. This allows developers to focus on the business logic of the application, reducing the time spent on configuration. Spring Boot provides its own embedded server (e.g., Tomcat, Jetty, etc.), enabling the application to run without the need for a separate web server installation.

3. What is OAuth2?

OAuth2 is an authentication framework that allows client applications to access user data securely. In other words, it provides a way for users to grant access to applications without exposing sensitive information like passwords. The basic flow of OAuth2 is as follows:

  1. User Authentication: When a user logs into the application, the application requests the user’s authorization from the OAuth service provider.
  2. Authorization Code Issuance: Once user authentication is complete, the OAuth service provider sends the Auth Code to the client application.
  3. Access Token Issuance: The client application requests an Access Token through the Authorization Code, which allows access to user data.

Through these steps, OAuth2 simplifies and secures the various user authentication processes.

4. Implementing OAuth2 in Spring Boot

In Spring Boot, OAuth2 can be easily implemented using spring-boot-starter-oauth2-client. Below is the OAuth2 setup process.

4.1. Adding Dependencies

First, you need to add the following dependency in the pom.xml file of your Maven project:

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

4.2. Configuring application.yml

Next, add the settings for the OAuth2 provider in the src/main/resources/application.yml file. For example, if you want to use Google OAuth2, you can set it up as follows:

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR_CLIENT_ID
            client-secret: YOUR_CLIENT_SECRET
            scope: profile, email
        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.3. Security Configuration

Next, configure security using Spring Security. Extend WebSecurityConfigurerAdapter and set it up as follows:

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

4.4. Login and Logout

To implement OAuth2 login, you can either use the default login screen provided or customize it. The logout feature is configured as follows:

http
    .logout()
        .logoutSuccessUrl("/")
        .permitAll();

Now, when you run the application, users can log in using OAuth2. Upon successful login, you will be able to view the user’s information.

5. What are Cookies?

Cookies are small pieces of data stored by web browsers, mainly used to store user session information. By using cookies, the server can maintain the client’s state, allowing the user to remain logged in even when refreshing the page or navigating to another page.

5.1. Characteristics of Cookies

  • Small Data Size: Cookies are typically limited to less than 4KB, and there is also a limit on the number of cookies a user can store in the browser.
  • Automatic Transmission: Cookies are automatically sent to the server when a request is made to that domain.
  • Expiration Settings: Cookies can have relative or absolute expiration times set.

5.2. Using Cookies in Spring

Using cookies in a Spring application is relatively straightforward. To add cookies to an HTTP response, you can handle it as follows:

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

// Creating and adding a cookie
public void addCookie(HttpServletResponse response) {
    Cookie cookie = new Cookie("name", "value");
    cookie.setMaxAge(60 * 60); // 1 hour
    cookie.setPath("/");
    response.addCookie(cookie);
}

5.3. Reading Cookies

To read cookies sent by the server, you can use HttpServletRequest:

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

// Reading a cookie
public void readCookie(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("name")) {
                String value = cookie.getValue();
                // Using the cookie
            }
        }
    }
}

6. Conclusion

In this course, we explored the process of implementing OAuth2 login and logout functionalities through Spring Boot, as well as the concept of cookies. OAuth2 is a powerful tool for flexibly handling user authentication across various platforms, while cookies help facilitate user session management. By properly utilizing these technologies in actual projects, strive to develop safer and more convenient web applications.

7. References

Spring Boot Backend Development Course, Implementing Login and Logout with OAuth2, Implementing Cookie Management Class

Hello! In this article, we will take a detailed look at how to implement login and logout using OAuth2 in backend development using Spring Boot, as well as the implementation of a cookie management class. User authentication and session management are very important elements in web applications. This article will introduce various concepts and technology stacks for these purposes.

Table of Contents

  1. 1. Overview of OAuth2
  2. 2. Spring Boot Setup
  3. 3. Implementing OAuth2 Login Feature
  4. 4. Implementing Logout Feature
  5. 5. Implementing Cookie Management Class
  6. 6. Conclusion

1. Overview of OAuth2

OAuth2 is a protocol primarily used for API authentication and authorization. It acts as an intermediary that allows safe access to others’ information. This protocol delegates authentication to a third-party service provider and helps protect user information.

For example, when a user can log in to another website using their Google account, OAuth2 is used. This method not only provides convenience for the user but also allows developers to avoid handling passwords directly.

1.1 Key Terms of OAuth2

  • Resource Owner: The user, or the owner of the resource.
  • Client: The application that requests user information.
  • Authorization Server: The server that performs user authentication and issues Access Tokens.
  • Resource Server: The server that grants access to protected resources.
  • Access Token: The authentication token used to access the resource server.

2. Spring Boot Setup

To implement OAuth2 using Spring Boot, we need to add the necessary dependencies, including spring-boot-starter-oauth2-client and spring-boot-starter-security.

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>

If you also plan to use MVC and the Thymeleaf template engine, you should include the following dependencies as well.


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

You need to add OAuth2-related configurations to the Spring Boot configuration file, application.yml. For example, you can set up Google login.

application.yml:
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

3. Implementing OAuth2 Login Feature

Once you have completed the necessary configurations for implementing OAuth2 login, let’s create a login page. You can easily add a simple login button using Thymeleaf.

login.html:
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Login Page</title>
</head>
<body>
    <h1>Please Log In</h1>
    <a href="@{/oauth2/authorization/google}">Log in with Google</a>
</body>
</html>

When you click the link to log in with Google, the OAuth2 flow begins. After the user logs in to Google and grants permission, the user’s information will return to the application.

3.1 Fetching User Information

To fetch user information after login, you can implement Spring Security’s UserDetailsService or OAuth2UserService.

UserService.java:
@Service
public class UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        OAuth2User oAuth2User = super.loadUser(userRequest);
        
        // Add business logic using user information
        
        return oAuth2User;
    }
}

Now, every time a user logs in, this service will be called to handle the user’s information.

4. Implementing Logout Feature

Now let’s implement the logout feature. Logging out terminates the user’s session, making the user information no longer valid.

LogoutController.java:
@Controller
public class LogoutController {

    @GetMapping("/logout")
    public String logout() {
        SecurityContextHolder.clearContext();
        // Additional logout handling logic
        return "redirect:/";
    }
}

After logging out, the user is redirected to the homepage. You can create a button for logging out as follows.

login.html:
<a href="@{/logout}">Logout</a>

Now, let’s implement a cookie management class to efficiently manage user sessions and data. Cookies are a way to store small data on the client side, which is useful for maintaining user state.

CookieManager.java:
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class CookieManager {

    public void createCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public String readCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public void deleteCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}

The above CookieManager class provides various methods for creating, reading, and deleting cookies.

5.1 Example of Using Cookies

Now let’s look at an example of actually using cookies. When a user logs in, you can store specific information in a cookie.

LoginController.java:
@PostMapping("/login")
public String login(@RequestParam String username, HttpServletResponse response) {
    // Login logic
    
    cookieManager.createCookie(response, "username", username, 60 * 60); // Persist for 1 hour
    return "redirect:/home";
}

The created cookie will be stored in the user’s browser and can be easily read in subsequent requests.

6. Conclusion

In this article, we specifically explored the implementation of OAuth2-based login and logout features using Spring Boot and the cookie management class for user session management. By using OAuth2, authentication can be easily handled, and through effective cookie management, user experience can be improved.

Now, you are equipped with the ability to implement user authentication and session management features through OAuth2 and cookie management in web applications based on Spring Boot. I hope this article will be helpful in your development journey.

Spring Boot Backend Development Course, Implementing Login and Logout with OAuth2, Adding Dependencies

Author: [Your Name]

Date: [Current Date]

1. Introduction

Modern applications commonly use the OAuth2 protocol for user authentication and authorization. This protocol helps to handle user information securely and flexibly across various client applications. In this tutorial, we will guide you step by step on how to implement login and logout features based on OAuth2 using Spring Boot.

2. Starting a Spring Boot Project

To start a Spring Boot project, the first step is to generate the basic project structure using Spring Initializr. Below are the initial setup procedures.

  1. Open a web browser and go to Spring Initializr.
  2. Set up the project metadata:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: Latest Stable Version
    • Group: com.example
    • Artifact: oauth2-demo
    • Name: oauth2-demo
    • Description: OAuth2 Example Application
  3. In the Dependencies section, add the following dependencies:
    • Spring Web
    • Spring Security
    • Spring Boot DevTools
    • Spring Data JPA
    • H2 Database (In-memory database for development and testing)
  4. Click ‘Generate’ to download the ZIP file and extract it to your desired directory.

3. Adding Dependencies

Now, open the Maven’s pom.xml file and add the OAuth2-related dependencies. Please add the following code to the `` section of pom.xml.

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

                    <dependency>
                        <groupId>org.springframework.security</groupId>
                        <artifactId>spring-security-oauth2-client</artifactId>
                    </dependency>

                    <dependency>
                        <groupId>org.springframework.security</groupId>
                        <artifactId>spring-security-oauth2-jose</artifactId>
                    </dependency>
                
            

Adding the above dependencies will allow you to use the default settings for the OAuth2 client. Next, you need to create an entity that can store user information using JpaRepository.

4. Setting Up User Entity and Repository

Create an entity class to store user information for the application. The code below is an example of the User entity that will hold user information.

                
                    package com.example.oauth2demo.model;

                    import javax.persistence.Entity;
                    import javax.persistence.GeneratedValue;
                    import javax.persistence.GenerationType;
                    import javax.persistence.Id;

                    @Entity
                    public class User {
                        @Id
                        @GeneratedValue(strategy = GenerationType.IDENTITY)
                        private Long id;

                        private String email;
                        private String name;

                        // Getters and Setters
                    }
                
            

Next, create a JpaRepository for the User entity.

                
                    package com.example.oauth2demo.repository;

                    import com.example.oauth2demo.model.User;
                    import org.springframework.data.jpa.repository.JpaRepository;

                    public interface UserRepository extends JpaRepository<User, Long> {
                        User findByEmail(String email);
                    }
                
            

5. Configuring OAuth2

To add OAuth2 login functionality, you need to configure the OAuth2 client in the application.yml file. Please refer to the example below.

                
                    spring:
                      security:
                        oauth2:
                          client:
                            registration:
                              google:
                                client-id: YOUR_CLIENT_ID
                                client-secret: YOUR_CLIENT_SECRET
                                scope:
                                  - email
                                  - profile
                            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
                
            

You need to register your Google API client here. You can create a client in the Google Cloud Console to obtain the client-id and client-secret.

6. Configuring Security

We will discuss how to set up Spring Security to handle OAuth2 login and logout. Write a SecurityConfig class and add HTTP security configurations.

                
                    package com.example.oauth2demo.config;

                    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", "/oauth2/**").permitAll()
                                    .anyRequest().authenticated()
                                .and()
                                    .oauth2Login()
                                        .defaultSuccessUrl("/home", true)
                                .and()
                                    .logout()
                                        .logoutSuccessUrl("/");
                        }
                    }
                
            

With this configuration, the root and login pages, as well as OAuth2-related URLs, are accessible to everyone, while only authenticated users can access other pages.

7. Writing the Controller

You need to write a controller to redirect users to the appropriate page after they log in using OAuth2. Below is an example of a basic controller.

                
                    package com.example.oauth2demo.controller;

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

                    @Controller
                    public class MainController {
                        @GetMapping("/")
                        public String index() {
                            return "index"; // Return index.html page
                        }

                        @GetMapping("/home")
                        public String home() {
                            return "home"; // Return home.html page
                        }
                    }
                
            

This controller returns index.html and home.html pages for the root path and home path, respectively.

8. Setting Up View Templates

Use Thymeleaf to set up the View templates. Create index.html and home.html in the resources/templates folder. Below is sample code for each file.

                
                    <!-- index.html -->
                    <!DOCTYPE html>
                    <html xmlns:th="http://www.thymeleaf.org">
                    <head>
                        <title>OAuth2 Login Example</title>
                    </head>
                    <body>
                        <h1>Welcome!</h1>
                        <a th:href="@{/oauth2/authorization/google}">Login with Google</a>
                    </body>
                    </html>
                
            
                
                    <!-- home.html -->
                    <!DOCTYPE html>
                    <html xmlns:th="http://www.thymeleaf.org">
                    <head>
                        <title>Home Page</title>
                    </head>
                    <body>
                        <h1>Welcome to the Home Page!</h1>
                        <a href="/logout">Logout</a>
                    </body>
                    </html>
                
            

9. Running the Application

Once all configurations are completed, run the application. You can either run the main class from your IDE or execute the following command in the terminal.

                
                    mvn spring-boot:run
                
            

If the application runs successfully, you can access the login screen at http://localhost:8080 in your web browser.

10. Conclusion

In this tutorial, we explored the implementation process of OAuth2 login/logout features using Spring Boot. This example provides an introduction to basic configurations, and in real projects, further security settings and management of user data should be considered. We encourage you to extend OAuth2 in a way that fits your project and implement user authentication features.

I hope this tutorial was helpful. Please leave your questions or feedback in the comments.

Spring Boot Backend Development Course, Implementing Login and Logout with OAuth2, Implementing and Applying OAuth2 with Spring Security

1. Introduction

The authentication and authorization mechanisms of modern applications are very important. OAuth2 is a widely used framework for handling authentication and authorization across various platforms. This tutorial will explain the login and logout process through OAuth2 using Spring Boot and Spring Security step by step. The goal is to build a secure API that includes user authentication features.

2. Spring Boot and Spring Security Project Setup

2.1. Installation Requirements

The following software is required to proceed with this tutorial:

  • JDK 11 or higher
  • Apache Maven
  • IDE (IntelliJ IDEA, Eclipse, etc.)

2.2. Project Creation

First, create a new Spring Boot project using Spring Initializr. For dependencies, add
Spring Web, Spring Security, and OAuth2 Client.

mvn clean install

3. OAuth2 Authentication Setup

3.1. OAuth2 Provider Configuration

There are various OAuth2 providers, and in this tutorial, we will use Google OAuth2. Create a new project in the Google Cloud Console and generate an OAuth 2.0 client ID.
The required information is the client ID and the client secret.

3.2. Application Properties Configuration

Add the following configuration to the src/main/resources/application.yml file:

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/userinfo/email
            user-name-attribute: email

4. Spring Security Configuration

4.1. Create Security Configuration Class

Create a class named SecurityConfig for basic Spring Security configuration. This class
extends WebSecurityConfigurerAdapter to define the security configuration.

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", "/oauth2/**").permitAll() // Allow all users for paths related to login
            .anyRequest().authenticated() // Other requests are accessible only to authenticated users
            .and()
            .oauth2Login(); // OAuth2 login configuration
    }
}

5. Login and Logout

5.1. Login Processing

OAuth2 login processing is automatically managed by Spring Security. When a user accesses the /login path, a login page is provided, and after login, they are redirected to the path set as the Redirect URI.

5.2. Logout Processing

Logout can be simply handled by setting the logout path. After logging out, the user can be redirected to the home page.

http.logout()
        .logoutSuccessUrl("/") // Redirect to home on logout
        .invalidateHttpSession(true); // Invalidate session

6. Create Client Application

To test login and logout, a simple client application will be created. Users can verify their information after authenticating through their Google account.

import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.userdetails.OAuth2UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    private final OAuth2UserService oAuth2UserService;
    private final ClientRegistrationRepository clientRegistrationRepository;

    public UserController(OAuth2UserService oAuth2UserService, ClientRegistrationRepository clientRegistrationRepository) {
        this.oAuth2UserService = oAuth2UserService;
        this.clientRegistrationRepository = clientRegistrationRepository;
    }

    @GetMapping("/user")
    public String getUserInfo(Principal principal) {
        return "User Info: " + principal.getName(); // Return user info
    }
}

7. Testing and Conclusion

Once all settings are complete, run the application and access the /login page. Click the Google login button to verify that the authentication process works correctly.
Upon successful login, user information can be verified at the /user path.

In this tutorial, you learned the basics of OAuth2 login/logout using Spring Boot. In the future, you can extend this with more complex authentication mechanisms using JWT,
and add custom features tailored to your company’s requirements.

© 2023 Spring Boot Development Blog