Spring Security 是一个功能强大且高度可定制的安全框架,用于保护 Spring 应用程序。以下是关键知识点:
核心概念 🔍
- 认证(Authentication):验证用户身份,如使用
UsernamePasswordAuthenticationToken
- 授权(Authorization):控制访问权限,依赖
@PreAuthorize
注解 - 安全配置:通过
SecurityFilterChain
定义规则 - 加密:支持
PasswordEncoder
实现密码安全存储
快速入门 🚀
- 添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
- 配置安全策略:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated(); return http.build(); }
关键特性 📦
- 基于角色的访问控制(RBAC):通过
@Secured
注解实现 - CSRF 防护:默认启用,可通过
csrf().disable()
禁用 - OAuth2 支持:集成第三方登录系统
- 方法级安全:细粒度控制业务方法权限
常见问题 ❓
- 如何实现登录页面自定义?
可通过继承WebSecurityConfigurerAdapter
并重写configure
方法 - 如何处理 JWT 认证?
推荐参考 JWT 配置文档