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

Spring Boot Backend Development Course, Implementing Login and Logout with OAuth2, Adding Author to Post

Hello! In this article, we will take a detailed look at how to perform backend development using Spring Boot. In particular, we will cover how to implement user authentication using OAuth2 and how to add author information to posts created by users.

1. What is Spring Boot?

Spring Boot is a framework that minimizes complex setup and enables rapid application development. It is based on the Spring framework and includes commonly used libraries and configurations, allowing for very efficient development of web applications.

1.1. Advantages of Spring Boot

  • It allows you to get started quickly and easily with the provided starter dependencies.
  • The auto-configuration feature reduces complex setups.
  • It can be run without separate server configurations through its embedded server.
  • Development is possible even without a deep understanding of Spring.

2. What is OAuth2?

OAuth2 is an authentication and authorization protocol that helps resource owners grant third-party applications access to their resources. It makes it easy to implement user authentication in various environments, such as web applications and mobile applications.

2.1. Key Components of OAuth2

  • Resource Owner: The user who grants access to a protected resource.
  • Client: The application that accesses the resource on behalf of the resource owner.
  • Authorization Server: The server that handles authentication and issues tokens.
  • Resource Server: The server that stores the protected resources.

3. Project Setup

To start developing a project using Spring Boot, we will use Spring Initializr. Please select the following dependencies:

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

After creating the project, add the necessary libraries through Maven or Gradle.

3.1. Adding Key Dependencies (Example of 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-security</artifactId>
    </dependency>
    <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>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
    </dependency>
</dependencies>

4. OAuth2 Configuration for User Authentication

4.1. application.yml Configuration

Configure the client information for the external service (e.g., Google, GitHub, etc.) that will use OAuth2 in the application.yml file.


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/userinfo/v2/me

4.2. Setting Up Security Configuration

Configure Spring Security to implement the OAuth2 login feature.


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(authorizeRequests ->
                authorizeRequests
                    .antMatchers("/", "/login", "/perform_login").permitAll()
                    .anyRequest().authenticated()
            )
            .oauth2Login(oauth2 -> oauth2
                .loginPage("/login")
            );
    }
}

5. Implementing Login and Logout Features

5.1. Creating a Custom Login Page

Create a custom login page using HTML and CSS. Here is an example:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Page</title>
</head>
<body>
    <h1>Login Page</h1>
    <a href="/oauth2/authorization/google">Login with Google</a>
</body>
</html>

5.2. Handling Logout

To configure the logout functionality, modify the SecurityConfig as follows.


@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests(authorizeRequests ->
            authorizeRequests
                .antMatchers("/", "/login", "/perform_login").permitAll()
                .anyRequest().authenticated()
        )
        .oauth2Login(oauth2 -> oauth2
            .loginPage("/login")
        )
        .logout(logout -> logout
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login?logout")
        );
}

6. Implementing the Writing Feature

Now, we will implement the functionality to save posts created by users in the database.

6.1. Creating the Entity Class

Create an Entity class for the post (including the author).


import javax.persistence.*;

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

    private String title;
    private String content;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private User author;

    // Getters and Setters
}

6.2. Creating the User Entity


import javax.persistence.*;

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

    private String username;
    private String email;

    // Getters and Setters
}

6.3. Creating Repository and Service

Create Repository and Service classes for writing posts.


// PostRepository.java
import org.springframework.data.jpa.repository.JpaRepository;

public interface PostRepository extends JpaRepository<Post, Long> {
}

// PostService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PostService {
    @Autowired
    private PostRepository postRepository;

    public List<Post> findAll() {
        return postRepository.findAll();
    }

    public Post save(Post post) {
        return postRepository.save(post);
    }
}

6.4. Creating the Controller

Create a Controller so that users can write and view posts.


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

import java.util.List;

@RestController
@RequestMapping("/posts")
public class PostController {
    @Autowired
    private PostService postService;

    @GetMapping
    public List<Post> getAllPosts() {
        return postService.findAll();
    }

    @PostMapping
    public Post createPost(@RequestBody Post post) {
        return postService.save(post);
    }
}

7. Conclusion

In this article, we discussed the basics of backend development using Spring Boot and how to implement user authentication and writing functionality using OAuth2. OAuth2 allows for easy implementation of various social media login features, which will be a great help in developing user-friendly web applications. In the next course, we will cover integration with the front end and, further, deployment. I hope this article has been helpful, and if you have any questions, please feel free to leave a comment!

Spring Boot Backend Development Course, Implementing Login and Logout with OAuth2, Adding Logic for Editing, Deleting Posts, and Verifying Authors

Table of Contents

  1. Introduction
  2. Introduction to Spring Boot
  3. Overview of OAuth2
  4. Implementing Login/Logout
  5. Implementing Post Edit and Delete Features
  6. Adding Author Confirmation Logic
  7. Conclusion

Introduction

Today, we will learn how to develop a backend application using Spring Boot. This tutorial will cover how to implement login and logout using OAuth2, as well as how to add functionality for editing and deleting posts and author confirmation logic. Through this process, you will learn to utilize various features of Spring Boot.

Introduction to Spring Boot

Spring Boot is a framework that supports easy application development based on the Spring Framework. It helps you build applications quickly without complex configurations and supports various embedded servers (e.g., Tomcat, Jetty, etc.). The main benefits of Spring Boot are:

  • Quick Start: Initial setup is simple, reducing development time.
  • Auto Configuration: Automatically sets up necessary libraries and dependencies.
  • Embedded Server: You can easily run applications locally without separate server configuration.
  • Strong Community: There is a vibrant user base and ample resources available for learning and problem-solving.

Overview of OAuth2

OAuth2 is an authentication protocol that allows client applications to obtain permission to access user resources. Through OAuth2, users can securely manage access permissions for applications. OAuth2 supports several authentication methods (e.g., Authorization Code, Implicit, Resource Owner Password Credentials, etc.) and is widely used in web and mobile applications.

In this tutorial, we will implement user authentication using OAuth2 and add features for creating, editing, and deleting posts with this authentication information. We will primarily use the Authorization Code Grant method.

Implementing Login/Logout

We will explore how to implement OAuth2-based login/logout functionality in a Spring Boot application. In this process, we will use Spring Security to handle authentication and authorization. Let’s proceed to the next steps.

1. Add Dependencies

First, we need to add the necessary dependencies to the Maven pom.xml file. Please add the following dependencies:


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

2. Configure application.yml

Now we need to configure the OAuth2 client information. Set the following in 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}"
                authorization-grant-type: authorization_code
            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/v2/me
    

3. Create SecurityConfig Class

Create a SecurityConfig class for secure application configuration. This class will handle the security settings of Spring Security.


    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", "/error/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .oauth2Login()
                    .defaultSuccessUrl("/home", true)
                    .failureUrl("/login?error");
        }
    }
    

4. Implement Login and Logout Controller

Create a HomeController class that will be called when users attempt to log in, handling the flow after login.


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

    @Controller
    public class HomeController {

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

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

At this point, basic login and logout functionality has been implemented. Users can now log in using their Google accounts.

Implementing Post Edit and Delete Features

Now that we have implemented basic login/logout functionality, we will add the ability to create, edit, and delete posts.

1. Create Entity and Repository for Posts

First, we need to create a Post entity and a JPA repository for it.


    import javax.persistence.*;
    import java.time.LocalDateTime;

    @Entity
    public class Post {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        
        private String title;
        private String content;

        @ManyToOne
        @JoinColumn(name="user_id")
        private User user; // Author information

        private LocalDateTime createdAt;
        private LocalDateTime updatedAt;

        // getters and setters
    }
    

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

    public interface PostRepository extends JpaRepository {
    }
    

2. Implement Post Creation and Editing Functionality

Create a controller to handle post creation and editing functionality.


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

    @Controller
    @RequestMapping("/posts")
    public class PostController {

        private final PostRepository postRepository;

        public PostController(PostRepository postRepository) {
            this.postRepository = postRepository;
        }

        @GetMapping("/new")
        public String newPost(Model model) {
            model.addAttribute("post", new Post());
            return "newpost"; // Post creation page
        }

        @PostMapping
        public String createPost(@ModelAttribute Post post, @AuthenticationPrincipal User user) {
            post.setUser(user); // Set the currently logged-in user
            post.setCreatedAt(LocalDateTime.now());
            postRepository.save(post);
            return "redirect:/posts";
        }

        @GetMapping("/{id}/edit")
        public String editPost(@PathVariable Long id, Model model) {
            Post post = postRepository.findById(id).orElseThrow();
            model.addAttribute("post", post);
            return "editpost"; // Post editing page
        }

        @PostMapping("/{id}")
        public String updatePost(@PathVariable Long id, @ModelAttribute Post post) {
            post.setId(id);
            post.setUpdatedAt(LocalDateTime.now());
            postRepository.save(post);
            return "redirect:/posts";
        }
    }
    

3. Implement Post Deletion Functionality

Add a method for deleting posts to the PostController.


    @DeleteMapping("/{id}")
    public String deletePost(@PathVariable Long id) {
        postRepository.deleteById(id);
        return "redirect:/posts";
    }
    

Adding Author Confirmation Logic

Finally, we add author confirmation logic to ensure that users can only edit or delete their own posts. To do this, we will add logic that compares the logged-in user’s information with the author of the post.


    @PostMapping("/{id}/edit")
    public String editPost(@PathVariable Long id, @AuthenticationPrincipal User user) {
        Post post = postRepository.findById(id).orElseThrow();
        if (!post.getUser().equals(user)) {
            throw new AccessDeniedException("You cannot edit this post."); // Access denied exception
        }
        return "editpost"; // Move to edit page
    }

    @DeleteMapping("/{id}")
    public String deletePost(@PathVariable Long id, @AuthenticationPrincipal User user) {
        Post post = postRepository.findById(id).orElseThrow();
        if (!post.getUser().equals(user)) {
            throw new AccessDeniedException("You cannot delete this post."); // Access denied exception
        }
        postRepository.deleteById(id);
        return "redirect:/posts";
    }
    

Conclusion

In this tutorial, we learned how to implement OAuth2-based login and logout functionality using Spring Boot, and how to add features for creating, editing, and deleting posts. Additionally, we established safeguards to ensure that users can only edit or delete their own posts through author confirmation logic. Through this process, we became acquainted with the basic usage of Spring Boot and OAuth2, gaining foundational knowledge necessary for actual application development.

We hope to continue learning about various features using Spring Boot and improve our skills further. Wishing you the best of luck on your development journey!