简介:本文是一篇完整的SpringSecurity学习教程,涵盖核心概念、配置方式、实战案例及最佳实践,帮助开发者快速掌握安全框架的配置与应用。
SpringSecurity是Spring生态中用于构建安全控制的核心框架,其核心功能包括认证(Authentication)、授权(Authorization)、攻击防护(CSRF/XSS等)及会话管理。与传统安全框架(如Shiro)相比,SpringSecurity的优势在于与Spring生态的无缝集成,支持基于注解的细粒度权限控制,且提供开箱即用的OAuth2、JWT等现代协议支持。
SpringSecurity的认证流程遵循过滤器链(FilterChainProxy)机制,核心组件包括:
典型流程示例:
// 自定义UsernamePasswordAuthenticationFilter示例public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {@Overridepublic Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) {String username = request.getParameter("username");String password = request.getParameter("password");UsernamePasswordAuthenticationToken token =new UsernamePasswordAuthenticationToken(username, password);return this.getAuthenticationManager().authenticate(token);}}
SpringSecurity采用基于角色的访问控制(RBAC)模型,通过以下方式实现:
@Secured("ROLE_ADMIN"))@PreAuthorize("hasAuthority('READ_PRIVILEGE')"))适用于遗留系统维护,示例:
<http><intercept-url pattern="/admin/**" access="hasRole('ADMIN')"/><form-login login-page="/login"/></http>
通过WebSecurityConfigurerAdapter实现:
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/public/**").permitAll().antMatchers("/admin/**").hasRole("ADMIN").anyRequest().authenticated().and().formLogin().loginPage("/login");}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password("{noop}pass").roles("USER").and().withUser("admin").password("{noop}admin").roles("ADMIN");}}
基于Lambda的DSL风格配置:
@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(auth -> auth.requestMatchers("/public/**").permitAll().anyRequest().authenticated()).formLogin(form -> form.loginPage("/login").defaultSuccessUrl("/home"));return http.build();}
添加依赖:
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-api</artifactId><version>0.11.5</version></dependency>
实现Token生成逻辑:
public class JwtTokenProvider {private final String secretKey = "your-secret-key";public String generateToken(Authentication authentication) {Date expiryDate = new Date(System.currentTimeMillis() + 86400000);return Jwts.builder().setSubject(authentication.getName()).claim("roles", authentication.getAuthorities()).setIssuedAt(new Date()).setExpiration(expiryDate).signWith(SignatureAlgorithm.HS512, secretKey).compact();}}
配置JWT过滤器:
public class JwtTokenFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain chain) {String token = request.getHeader("Authorization");if (token != null) {// 解析Token并设置SecurityContext}chain.doFilter(request, response);}}
@Configuration@EnableResourceServerpublic class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/api/**").authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);}}
http.csrf().disable())XssFilterX-Frame-Options头
http.headers().frameOptions().disable() // 允许iframe嵌入(谨慎使用).httpStrictTransportSecurity().and().contentSecurityPolicy("default-src 'self'");
结合SpringSecurity与GoogleAuthenticator:
public class GoogleAuthenticatorFilter extends AbstractAuthenticationProcessingFilter {@Overridepublic Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) {String code = request.getParameter("code");// 验证TOTP代码逻辑}}
@PreAuthorize注解是否正确UserDetails的getAuthorities()方法
http.sessionManagement().invalidSessionUrl("/login?timeout=true").maximumSessions(1).expiredUrl("/login?expired=true");
@Beanpublic WebMvcConfigurer corsConfigurer() {return new WebMvcConfigurer() {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("https://yourdomain.com").allowedMethods("*");}};}
本教程系统梳理了SpringSecurity的核心知识体系,从基础配置到高级实践均有详细说明。建议开发者通过实际项目巩固学习成果,重点关注权限模型的合理设计和安全漏洞的预防措施。随着SpringSecurity 6.x的发布,响应式编程支持将成为新的学习重点,建议持续关注官方更新。