Spring Boot Backend Development Course, What is ORM

Spring Boot is a framework that helps develop Java-based web applications easily. In this tutorial, we will cover one of the key concepts of Spring Boot, which is ORM (Object-Relational Mapping). ORM is a technology that simplifies interaction between the object-oriented programming language Java and relational databases. In this article, we will delve deeply into various topics such as the definition of ORM, its advantages, usage, integration with Spring Boot, and more.

Definition of ORM

ORM is a technology that provides mapping between objects used in object-oriented programming languages and tables used in relational databases. Simply put, ORM allows database data to be represented as objects in object-oriented languages. As a result, developers can interact with the database without the need to write SQL queries. Common implementations of ORM include Hibernate, JPA (Java Persistence API), and more.

History of ORM

The concept of ORM can be traced back to the late 1980s. It first emerged to provide a concise interaction with databases along with the advancement of object-oriented languages. Gradually, ORM technologies gained recognition for their utility and productivity and became widely used in various frameworks and libraries. In the Java ecosystem, JPA and Hibernate have solidified their position as the leading implementations of ORM.

Advantages of ORM

Using ORM provides several advantages:

  • Increased Productivity: By using ORM, developers do not need to write SQL queries directly, which greatly enhances development productivity.
  • Easier Maintenance: Even if the database structure changes, due to object mapping, less code modification is needed, making maintenance easier.
  • Object-Oriented Development: The representation of database data as objects allows for maximum utilization of the advantages of object-oriented programming.
  • Database Independence: Using ORM enables the development of applications independently of specific database vendors.

Disadvantages of ORM

Of course, ORM is not without its disadvantages. Here are some drawbacks of using ORM:

  • Performance Issues: Since ORM automatically generates SQL, performance issues can arise. Incorrect query generation or unnecessary JOINs can be problematic.
  • Limitations of Abstraction: There may be cases where the abstraction provided by ORM cannot accurately represent all data, and there may still be a need to use SQL for complex queries.
  • Learning Curve: There can be a learning curve for users who are new to ORM frameworks. This is especially true in cases with complex mappings.

Using ORM in Spring Boot

Spring Boot uses JPA as its default ORM. JPA is a set of interfaces that define the mapping between Java objects and relational databases. In Spring Boot, you can easily apply ORM by adding JPA as a dependency.

JPA and Hibernate

JPA is a standard interface, and Hibernate is an ORM framework that implements this standard interface. By using Hibernate, you can manage interactions with the database through JPA, allowing for easy execution of CRUD (Create, Read, Update, Delete) operations on the database. Now, let’s look at actual code examples to see how to use JPA and Hibernate.

Setting Up the Environment

First, to use JPA and Hibernate in a Spring Boot project, you need to add the following dependencies. Add the following to the pom.xml file using Maven:


    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    

Defining the Entity Class

Next, define the entity class that will be mapped to the database. For example, let’s create an entity class called User:


    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 name;
        private String email;

        // Getters and Setters
    }
    

Writing the Repository Interface

Write a repository interface to perform CRUD operations:


    import org.springframework.data.jpa.repository.JpaRepository;

    public interface UserRepository extends JpaRepository<User, Long> {
    }
    

Writing the Service Class

Now, you can implement business logic through the service class:


    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import java.util.List;

    @Service
    public class UserService {
        @Autowired
        private UserRepository userRepository;

        public User createUser(User user) {
            return userRepository.save(user);
        }

        public List<User> getAllUsers() {
            return userRepository.findAll();
        }
    }
    

Writing the Controller Class

Finally, write a controller class to provide the REST API:


    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;

    import java.util.List;

    @RestController
    @RequestMapping("/api/users")
    public class UserController {
        @Autowired
        private UserService userService;

        @PostMapping
        public ResponseEntity<User> createUser(@RequestBody User user) {
            return ResponseEntity.ok(userService.createUser(user));
        }

        @GetMapping
        public ResponseEntity<List<User>> getAllUsers() {
            return ResponseEntity.ok(userService.getAllUsers());
        }
    }
    

Conclusion

In this tutorial, we explored what ORM is in Spring Boot and how to interact with databases through it. ORM is a powerful tool that enhances development productivity and simplifies maintenance. The method of interacting with the database using JPA and Hibernate is relatively straightforward, and these technologies make backend development much easier.

In future tutorials, we will delve into more examples and advanced features of ORM. Please look forward to more content on backend development using Spring Boot!

Spring Boot Backend Development Course, Implementing Login and Logout with OAuth2, Obtaining Tokens

In recent years, the security and user authentication methods of web applications have changed dramatically. In particular, OAuth2 has established itself as the standard for handling user authentication in many web services. This course will detail how to implement login and logout using OAuth2 with Spring Boot, as well as the token issuance process. Through this article, you will learn the basic principles of OAuth2 and gain the skills needed to build real applications.

1. What is OAuth2?

OAuth2 is a protocol for user authentication that allows users to grant access without providing their information to third-party services. This enables apps or services to access the user’s resources. The main components of OAuth2 are as follows:

  • User (Resource Owner): The entity that protects and manages their information.
  • Client: An application that seeks to access resources on behalf of the user.
  • Resource Server: The server that provides protected resources.
  • Authorization Server: The server that handles user authentication and issues access tokens to the client.

2. What is Spring Boot?

Spring Boot is a project based on Java’s Spring Framework that helps in quickly developing applications. Spring Boot offers the following advantages:

  • Simplified configuration: Thanks to various defaults, you can get started quickly without complex configurations.
  • Auto-configuration: You can easily add the necessary libraries for automatic configuration.
  • Starter packages: These provide starter packages that combine multiple dependencies and configurations to speed up development.

3. Preparing to Build an OAuth2 Login System

3.1 Project Setup

To start a Spring Boot project, use Spring Initializr to create a basic project. Add the following dependencies:

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

3.2 Project Structure

        /src
        └── main
            ├── java
            │   └── com
            │       └── example
            │           └── oauth2demo
            │               ├── controller
            │               ├── model
            │               ├── repository
            │               ├── security
            │               └── service
            └── resources
                ├── application.properties
                └── static
    

3.3 Configuring application.properties

To use OAuth2, configure as below. I will use Google OAuth2 as an example:

        spring.security.oauth2.client.registration.google.client-id=YOUR_CLIENT_ID
        spring.security.oauth2.client.registration.google.client-secret=YOUR_CLIENT_SECRET
        spring.security.oauth2.client.registration.google.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}
        spring.security.oauth2.client.registration.google.scope=profile, email
        spring.security.oauth2.client.provider.google.authorization-uri=https://accounts.google.com/o/oauth2/auth
        spring.security.oauth2.client.provider.google.token-uri=https://oauth2.googleapis.com/token
        spring.security.oauth2.client.provider.google.user-info-uri=https://www.googleapis.com/oauth2/v3/userinfo
    

4. Spring Security Configuration

Spring Security is used to manage authentication and authorization. Below is a basic security configuration example:

    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()
                .anyRequest().authenticated()
                .and()
                .oauth2Login();
        }
    }
    

5. Retrieving User Information

Once the user has completed the login, the client application can obtain the authentication information. To fetch user’s information, implement the service below:

    import org.springframework.security.core.Authentication;
    import org.springframework.security.oauth2.core.user.OAuth2User;
    import org.springframework.stereotype.Service;

    @Service
    public class UserService {
        public String getCurrentUserName(Authentication authentication) {
            OAuth2User oauth2User = (OAuth2User) authentication.getPrincipal();
            return oauth2User.getAttribute("name");
        }
    }
    

6. Implementing Logout

Logout is also a common requirement. You can implement a simple logout feature using the configuration below:

    http
        .logout()
        .logoutSuccessUrl("/login")
        .invalidateHttpSession(true)
        .clearAuthentication(true);
    

7. Running and Testing the Application

After completing all configurations, run the application and access http://localhost:8080 in your web browser. If configured correctly, the Google login screen will appear. You will also be able to view a screen that retrieves the user’s name after logging in.

8. Conclusion

In this course, we explored how to implement login and logout functions based on OAuth2 using Spring Boot. OAuth2 is a widely used authentication method in modern web applications, and we have seen how easily it can be configured using Spring Boot. We hope to build a more secure and convenient user authentication system by adding more advanced features in the future.

Additional Resources

If you would like more information, please refer to the links below:

Spring Boot Backend Development Course, Adding Approved URI to OAuth Service

Modern web applications require user authentication and authorization management. OAuth 2.0 is one of the popular protocols for such authentication, allowing users to securely access services without exposing their credentials to third-party applications. This tutorial will guide you step-by-step on how to add authorized URIs to an OAuth service using Spring Boot.

1. Overview of OAuth

OAuth 2.0 is a protocol for user authentication, widely used primarily in web applications. When using OAuth, users receive a token that allows them to access other services without providing their login information. OAuth 2.0 supports many different authentication providers, each requiring a URI to process authentication requests.

2. Integrating Spring Boot with OAuth

Using Spring Boot makes it easy to implement OAuth 2.0 authentication. This process aims to set up an OAuth 2.0 client using Spring Security and add authorized URIs to the service.

2.1. Project Setup

To start a Spring Boot project, add the dependencies for spring-boot-starter-web and spring-boot-starter-security. Additionally, you will also need the dependency for spring-boot-starter-oauth2-client to use OAuth 2.0 clients.

    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</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-oauth2-client</artifactId>
    </dependency>

3. Understanding the Authorized URI

In OAuth 2.0, the authorized URI is the address where users will be redirected after authentication. This URI is specified when registering the client, and the authentication service redirects to this URI to send the response after user authentication. It may include an access token along with user information.

4. Adding Authorized URI in Spring Boot

4.1. Configuring application.yml

In Spring Boot, you can set up OAuth client properties through the application.yml or application.properties file. Here is an example of configuring a Google OAuth 2.0 client.


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

4.2. Configuring Web Security

To use OAuth 2.0 authentication, you need to add web security configuration. The following settings ensure that only authenticated users can access certain paths.


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() // Paths accessible without login
                .anyRequest().authenticated() // All other requests require authentication
                .and()
            .oauth2Login(); // OAuth 2.0 login
    }
}

4.3. Testing the Authorized URI

You can now run Spring Boot and navigate to http://localhost:8080 to test the OAuth login. A Google login button will appear, allowing users to authenticate.

5. Monitoring the Authorized URI

It is important to understand how the authorized URI works in an OAuth 2.0 application. Let’s look at several issues that may arise in this process and their solutions.

5.1. Redirection Errors

If the redirection URI is set incorrectly, users may not be redirected to the appropriate page after authentication. In such cases, you need to ensure that the authorized redirection URI is entered correctly when registering the client. For example:

    
    redirect-uri: http://localhost:8080/login/oauth2/code/google

5.2. Scope Issues

Problems can also occur if the requested scopes are set incorrectly. If the scopes are set wrong, the authentication may fail, so pay attention to scope settings.

6. Implementing Additional Features

Now that we have set the basic OAuth 2.0 elements, we can implement features that display additional information after user authentication or control conditional access rights. For instance, let’s look at how to retrieve user profile information and display it on a web page.

6.1. Fetching User Information


import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserController {

    @GetMapping("/user")
    public String user(@AuthenticationPrincipal OAuth2AuthenticationToken authentication, Model model) {
        model.addAttribute("user", authentication.getPrincipal().getAttributes());
        return "user"; // Navigate to user.html
    }
}

6.2. Displaying User Information

To display user information, you can create a simple HTML template. Create a file named src/main/resources/templates/user.html and add the following code.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Information</title>
</head>
<body>

<h1>User Information</h1>
<ul>
    <li>Name: <span th:text="${user['name']}"></span></li>
    <li>Email: <span th:text="${user['email']}"></span></li>
</ul>

</body>
</html>

7. Conclusion

In this tutorial, we learned how to set up OAuth 2.0 authentication using Spring Boot and add authorized URIs. Implementing user authentication through the OAuth protocol provides a secure and convenient user experience. You can now add these functionalities to your projects and explore integrations with various APIs.

To fully utilize all features of OAuth 2.0, it’s advisable to refer to various libraries and documentation. For more in-depth information, please consult the official OAuth 2.0 documentation.

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