Spring Boot 3 整合 Spring Security 实现登录校验与权限认证
在现代 web 应用中,安全性是一个非常重要的方面。Spring Security 是一个强大的安全框架,能够为基于 Spring 的应用提供全面的安全性。本文将涵盖如何在 Spring Boot 3 中整合 Spring Security,实现用户登录校验与权限认证,本文将提供详尽的代码示例。
一、项目环境准备
首先,我们需要创建一个 Spring Boot 项目。可以使用 Spring Initializr(https://start.spring.io/)来快速生成项目。选择依赖项时,确保添加以下依赖:
- Spring Web
- Spring Security
- Spring Data JPA
- H2 Database(可选,用于测试)
二、项目结构
假设我们的项目结构如下:
src
└── main
├── java
│ └── com
│ └── example
│ └── securitydemo
│ ├── SecurityDemoApplication.java
│ ├── config
│ │ └── SecurityConfig.java
│ ├── controller
│ │ └── UserController.java
│ ├── entity
│ │ └── User.java
│ ├── repository
│ │ └── UserRepository.java
│ └── service
│ └── UserService.java
└── resources
└── application.properties
三、实体类
先创建一个 User
实体类,用于存储用户信息:
package com.example.securitydemo.entity;
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 username;
private String password;
private String role;
// Getters and Setters
}
四、数据访问层
创建 UserRepository
接口来访问数据:
package com.example.securitydemo.repository;
import com.example.securitydemo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
五、服务层
创建 UserService
来处理用户业务逻辑:
package com.example.securitydemo.service;
import com.example.securitydemo.entity.User;
import com.example.securitydemo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
public User createUser(String username, String password, String role) {
User user = new User();
user.setUsername(username);
user.setPassword(passwordEncoder.encode(password));
user.setRole(role);
return userRepository.save(user);
}
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
}
六、安全配置
接下来是配置 Spring Security 的部分:
package com.example.securitydemo.config;
import com.example.securitydemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(username -> {
var user = userService.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return new UserDetailsImpl(user);
});
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
七、控制层
创建一个简单的控制器 UserController
用于处理用户请求:
package com.example.securitydemo.controller;
import com.example.securitydemo.entity.User;
import com.example.securitydemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public User register(@RequestParam String username, @RequestParam String password, @RequestParam String role) {
return userService.createUser(username, password, role);
}
@GetMapping("/hello")
public String hello() {
return "Hello, authenticated user!";
}
}
八、应用配置
在 application.properties
文件中,你可以配置数据库和其他设置。例如:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=create-drop
九、总结
通过上述步骤,我们已经实现了一个简单的用户注册和登录功能,并使用 Spring Security 进行了权限控制。你可以根据自己的需求进一步扩展功能,例如添加注销功能、角色权限控制等。
当然,在实际应用中,请务必加以注意安全性问题,如加密存储用户密码、使用 HTTPS 等。希望这篇文章能帮助到你,让你在 Spring Boot 和 Spring Security 的学习中有所收获!