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.