Spring Boot Security 是 Spring 生态系统中用于构建安全应用程序的核心模块,支持认证、授权、加密等安全功能。以下是关键知识点概览:
1. 基础配置
- 添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
- 启用安全功能:
在application.properties
中配置spring.security.user.name
和spring.security.user.password
👉 查看完整配置示例
2. 认证与授权
- 支持多种认证方式:表单登录、OAuth2、JWT 等
- 基于角色的访问控制(RBAC):
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin").hasRole("ADMIN") .anyRequest().authenticated(); } }
3. 安全性最佳实践
- 🔒 使用 HTTPS:在
application.properties
中启用server.port=8443
并配置 SSL - 🔒 密码加密:默认使用 BCrypt,可通过
spring.security.user.password-encoder
自定义 - 🛡️ 防止 CSRF 攻击:默认启用,如需关闭需谨慎评估风险
4. 扩展功能
- 集成 OAuth2:OAuth2 配置指南
- 动态权限管理:通过
@PreAuthorize
注解实现方法级权限控制 - 安全过滤器链:自定义过滤器增强安全逻辑
Spring_Boot_Security_Architecture
Spring Boot Security 架构图
如需深入学习,可参考 Spring Security 官方文档 或 Spring Boot 安全性专题。