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: