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.