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!