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

Spring Boot Backend Development Course, Implementing Login and Logout with OAuth2, Writing OAuth2 Configuration Files

1. Introduction

Recently, with the increasing development of web applications based on microservices architecture and cloud services, the popularity of frameworks like Spring Boot is rising.
Spring Boot is a framework that helps to quickly develop applications without complex configuration.
In this tutorial, we will learn in detail how to implement login and logout functionalities using OAuth2 in backend development with Spring Boot.

2. What is OAuth2?

OAuth2 is an authentication protocol that allows users to control access to the client application.
With OAuth2, users can perform authentication and authorization for specific resources without sharing their credentials with the application.
This is a way to enhance security and significantly improve user experience.

2.1 Key Components of OAuth2

  • Resource Owner: The user who grants permission to a client application
  • Client: The application attempting to access the Resource Owner’s resources
  • Resource Server: The server that stores the user’s resources
  • Authorization Server: The server that processes the user’s authentication information and issues tokens to the client

3. Setting Up a Spring Boot Project

To start a Spring Boot application, first create a new project.
You can generate a Maven or Gradle based project using Spring Initializr.

3.1 Adding Dependencies

To implement OAuth2 authentication, you need to add the following dependencies:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.0.RELEASE'
}

3.2 Configuring application.properties

Next, open the src/main/resources/application.properties file to add the necessary configurations for OAuth2 authentication.
Refer to the example configuration below.


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.scope=profile, email
spring.security.oauth2.client.registration.google.redirect-uri=http://localhost:8080/login/oauth2/code/google
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. Implementing OAuth2 Login

Now, let’s implement OAuth2 login in the application. This can be easily configured through Spring Security.

4.1 Security Configuration

Create a new Java class to configure the security settings.

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**", "/error**").permitAll()
                .anyRequest().authenticated()
                .and()
            .oauth2Login();
    }
}

5. Retrieving User Profile

Once the user logs in, you can request user information from the OAuth2 server to retrieve the profile.
We will write a controller for this purpose.

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 UserProfileController {
    @GetMapping("/user")
    public String user(@AuthenticationPrincipal OAuth2User principal, Model model) {
        model.addAttribute("name", principal.getAttribute("name"));
        model.addAttribute("email", principal.getAttribute("email"));
        return "userProfile";
    }
}

6. Implementing Logout

The logout functionality is provided by Spring Security by default, and it can be easily implemented through configuration.
Add the logout URL and related settings as shown below.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/login**", "/error**").permitAll()
                .anyRequest().authenticated()
                .and()
            .oauth2Login()
                .and()
            .logout()
                .logoutSuccessUrl("/")
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID");
    }

7. Conclusion

In this tutorial, we explored a simple way to implement login and logout functionalities using OAuth2 with Spring Boot.
Using Spring Boot and OAuth2 allows for easy integration with external authentication systems, greatly enhancing application security and improving user experience.
Consider applying OAuth2 to your projects to provide safer and more convenient services!

8. Additional Resources

For more information, please refer to the official documentation and other resources.

Spring Boot Backend Development Course, What is NoSQL

In recent years, the paradigm of software development has changed significantly. Especially with the explosive increase in the amount of data, new methods of database management have become necessary. While traditional relational databases are still widely used, NoSQL databases are emerging, creating a new trend. In this article, we will explain in detail what NoSQL is in Spring Boot backend development, when it should be used, and the types and characteristics of NoSQL databases.

Concept of NoSQL

NoSQL stands for “Not Only SQL,” referring to a data storage model developed as an alternative to traditional relational database management systems (RDBMS). NoSQL supports various data models, providing the capability to flexibly store and query large amounts of unstructured or semi-structured data that relational databases find difficult to handle.

The main features of NoSQL are as follows:

  • Schema Flexibility: NoSQL databases do not have a fixed schema, allowing for easy adaptation even if the data structure changes.
  • Horizontal Scalability: As the volume of data increases, servers can be added to the cluster to scale horizontally.
  • High Availability: To maintain high availability even when failures occur, replication and distributed storage capabilities are provided.

The Need for NoSQL

The reasons for the need for NoSQL are primarily as follows.

  • Handling Large Amounts of Data: It is useful when large-scale data collection and storage are needed, such as IoT, social media, and log data.
  • Unstructured Data: While relational databases are optimized for structured data, NoSQL is suitable when it is necessary to store images, videos, and data in various formats.
  • Fast Development: It allows for quick adaptation to dynamic data structures, improving the speed of application development.

Types of NoSQL Databases

NoSQL databases can be classified into various types, each of which is suitable for specific use cases based on its characteristics.

1. Key-Value Store

A key-value store is a structure where data is stored as key-value pairs. It offers a simple structure and fast query speed, making it suitable for session management, caching, and simple data storage. Examples include Redis and DynamoDB.

2. Document Store

A document store saves data in document formats such as JSON, BSON, and XML. The schema for the data is flexible, allowing other structured data to be stored within the same document. MongoDB and CouchDB are representative examples.

3. Column-Family Store

A column-family store is optimized for handling large volumes of data by storing data in column units. By keeping frequently used columns in memory, performance can be improved. Apache Cassandra and HBase are typical examples.

4. Graph Database

A graph database stores data represented as nodes and edges. It is suitable for data models where relationships are significant and is commonly used in social network analysis. Neo4j is well known in this category.

Integration of Spring Boot and NoSQL

Spring Boot supports various Spring Data projects for integration with NoSQL databases. In this section, we will look at a simple integration example with MongoDB using Spring Boot.

1. Adding Dependencies

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
    

2. MongoDB Configuration

Add the connection settings for MongoDB in the application.properties file.

        spring.data.mongodb.uri=mongodb://localhost:27017/testdb
    

3. Creating Domain Class

    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.mapping.Document;

    @Document(collection = "user")
    public class User {
        @Id
        private String id;
        private String name;
        private String email;

        // getters and setters
    }
    

4. Creating Repository

    import org.springframework.data.mongodb.repository.MongoRepository;

    public interface UserRepository extends MongoRepository<User, String> {
        User findByName(String name);
    }
    

5. Creating Service and Controller

    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 List<User> getAllUsers() {
            return userRepository.findAll();
        }

        public User getUserByName(String name) {
            return userRepository.findByName(name);
        }
        
        public void createUser(User user) {
            userRepository.save(user);
        }
    }
    

Conclusion

NoSQL databases play an important role in modern web applications, helping developers meet various data processing requirements. By using them with Spring Boot, they offer higher productivity and flexibility, especially demonstrating their value in unstructured data environments. Through this course, I hope to summarize the essence of NoSQL and its practical use cases in Spring Boot.

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

In today’s lecture, we will learn in detail how to implement login and logout functionality based on OAuth2 using Spring Boot. OAuth2 is a representative authentication protocol that enables efficient and secure authentication through integration with external services. Through this article, we will explain step by step how to implement OAuth2 services in Spring Boot with practical examples.

1. What is OAuth2?

OAuth2 is a protocol that allows a third-party application to access the resources of a resource owner. This enables users to access applications without the need to share their passwords. OAuth2 has two main roles:

  • Resource Owner: Typically refers to the user, who grants permission to provide their data to a third-party service.
  • Client: The application that requests the user’s data.

1.1 Key Components of OAuth2

  • Authorization Server: The server that handles user authentication and authorization.
  • Resource Server: The server that provides protected resources (e.g., API).
  • Client Credentials: Information that identifies the application.
  • Access Token: A token representing access rights to the resource server.

2. Setting Up Spring Boot Environment

To set up OAuth2 using Spring Boot, you first need to add the required dependencies. You can use Gradle or Maven. Here, we will explain it based on Maven.

2.1 Adding Maven Dependencies

pom.xml
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <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>
</dependencies>

2.2 Configuring application.properties

Add the basic configuration that the OAuth2 client will use in the application.properties file.

application.properties
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=email,profile
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
spring.security.oauth2.client.provider.google.user-name-attribute=sub

Note: The YOUR_CLIENT_ID and YOUR_CLIENT_SECRET placeholders must be replaced with the credentials of the OAuth 2.0 client created in the Google Developer Console.

3. Implementing OAuth2 Login/Logout

Now that we have completed the basic setup for applying OAuth2, we will proceed to implement the login and logout functionalities.

3.1 Security Configuration

We configure security settings for the web application using Spring Security. Add the following code to the SecurityConfig.java class:

SecurityConfig.java
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", "/css/**", "/js/**").permitAll()
                .anyRequest().authenticated()
            .and()
            .logout()
                .logoutSuccessUrl("/")
                .permitAll()
            .and()
            .oauth2Login();
    }
}

3.2 Implementing the Login Page

To create a login page, create a login.html file and add the following content:

login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h1>Login Page</h1>
    <a href="/oauth2/authorization/google">Login with Google</a>
</body>
</html>

3.3 Handling User Information

Let’s learn how to handle user information after login. You can retrieve user information by implementing OAuth2UserService.

CustomOAuth2UserService.java
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;

@Service
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        // Handling user information
        // For example, saving user information to the database or adding it to the session
    }
}

4. Implementing OAuth2 Logout

The logout functionality can be easily implemented using the built-in Spring Security features. Since we have set the URL to redirect after logout success in the SecurityConfig class, you just need to add a logout button.

4.1 Adding a Logout Button

Add a logout button to the main page so that users can log out. A basic HTML code might look like this:

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home Page</title>
</head>
<body>
    <h1>Welcome!</h1>
    <a href="/logout">Logout</a>
</body>
</html>

5. Conclusion

In today’s lecture, we explored how to implement login and logout functionality through OAuth2 using Spring Boot. OAuth2 is a useful method that leverages external services to facilitate user authentication in a simpler and more secure manner. I hope this lecture helped you understand the process of setting up Spring Boot and OAuth2, and that you learned practical implementation methods.

5.1 Additional Resources

If you want more in-depth content, please refer to the resources below:

Spring Boot Backend Development Course, Configuring the Main Directory

Spring Boot is a Java-based framework that helps developers build applications easily without complex configurations. This course will cover how to structure the main directory of a Spring Boot project. This directory serves as the starting point for a Java application and is where the important business logic is implemented.

Spring Boot Project Structure

A Spring Boot project follows a predefined structure. When you create a Spring Boot project in your IDE, a basic structure like the one below is generated.

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── demo
│   │               ├── DemoApplication.java
│   │               └── controller
│   │               └── service
│   │               └── repository
│   └── resources
│       ├── application.properties
│       └── static
│       └── templates
└── test
    └── java

1. src/main/java Directory

The src/main/java directory is where the actual Java source code is located, and each package and class file is stored here. In Spring Boot, packages are generally structured in the format of com.example.demo.

1.1 Main Application Class

The DemoApplication.java file is the entry point of the Spring Boot application. This class is annotated with @SpringBootApplication, which encompasses the following three functionalities:

  • @Configuration: A Java-based configuration class.
  • @EnableAutoConfiguration: Enables Spring Boot’s auto-configuration feature.
  • @ComponentScan: Automatically scans the specified packages to discover Spring components.

Below is an example of the main application class.

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

1.2 Package Structure

When there are many source files, defining an appropriate package structure is important. Typically, packages such as controller, service, and repository are defined.

Controller Package

The controller package contains methods that handle requests and return responses. In a RESTful API, the @RestController annotation is mainly used to set up the REST API server.

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}

Service Package

The service package includes classes that handle business logic. The classes here are registered in the Spring context using the @Service annotation.

package com.example.demo.service;

import org.springframework.stereotype.Service;

@Service
public class HelloService {
    public String getGreeting() {
        return "Hello from Service!";
    }
}

Repository Package

The repository package is responsible for interacting with the database. It usually extends JpaRepository to provide CRUD functionality.

package com.example.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.User;

@Repository
public interface UserRepository extends JpaRepository {
}

2. src/main/resources Directory

The src/main/resources directory is where static files, templates, and configuration files used by the application are located. The main files and directories in this location are as follows.

2.1 application.properties

The configuration file application.properties is responsible for application environment settings. Here, you can set database configurations, port numbers, log levels, etc.

spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=password
server.port=8080
logging.level.org.springframework=DEBUG

2.2 static Directory

The static directory is where static resources like CSS, JavaScript, and image files are stored. Spring Boot automatically serves all files in this directory.

2.3 templates Directory

The templates directory is used to dynamically generate HTML files using a template engine like Thymeleaf. You can create HTML files here and inject dynamic data.





    Welcome


    

Welcome Message

3. src/test/java Directory

The src/test/java directory contains sources related to the application’s tests. Unit tests and integration tests are performed using testing frameworks like JUnit and Mockito.

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class DemoApplicationTests {
    
    @Autowired
    private HelloService helloService;

    @Test
    void contextLoads() {
        assertNotNull(helloService);
    }
}

Conclusion

In this course, we have explored in detail how to structure the main directory of a Spring Boot project. By understanding the project structure and configuring it correctly, developers can write more efficient and maintainable code. This structure will significantly aid in future maintenance and collaboration. Wishing you successful Spring Boot backend development.