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.
- Open a web browser and go to Spring Initializr.
- 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
- 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)
- 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 `
<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.