Spring Security 教程(05)、Java配置

Java Config 的优势

java-configuration 配图
java-configuration 配图
java-configuration 配图

Spring Security 3.2 引入了基于 Java 的配置方式,替代传统的 XML 配置。Java Config 有以下几个明显优势:

类型安全:编译期检查,配置错误在编译阶段就能发现,而不是运行时。

可重构:IDE 的重构工具(重命名、移动、查找引用)对 Java Config 完全有效,XML 做不到。

可调试:你可以像调试普通 Java 代码一样调试安全配置,设置断点、查看变量值。

可组合:Java Config 支持将安全配置拆分成多个类,通过 @Bean 组合,比 XML 的 include/import 更加灵活。

核心配置类

Spring Security 4.x 推荐使用 WebSecurityConfigurerAdapter 作为安全配置的基础类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("admin123"))
.roles("ADMIN");
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

configure(HttpSecurity):URL 级别的配置

configure(HttpSecurity) 方法负责配置 URL 级别的授权规则。通过链式调用,你可以精确控制每个请求的安全策略。

关键方法:

  • authorizeRequests():开始配置请求授权规则
  • requestMatchers():指定要匹配的 URL 模式
  • permitAll():允许所有请求,无需认证
  • authenticated():要求认证
  • hasRole() / hasAuthority():基于角色或权限的访问控制
  • formLogin():启用表单登录
  • httpBasic():启用 HTTP Basic 认证
  • logout():配置登出行为

configure(AuthenticationManagerBuilder):认证方式配置

configure(AuthenticationManagerBuilder) 方法负责配置用户来源和认证方式。

常见的认证后端:

  • inMemoryAuthentication():内存中存储用户信息(适合开发测试)
  • jdbcAuthentication():从数据库查询用户信息
  • ldapAuthentication():连接 LDAP 目录服务
  • authenticationProvider():注入自定义认证提供者

configure(WebSecurity):忽略静态资源和全局配置

configure(WebSecurity) 方法用于配置全局安全行为,比如忽略某些 URL 模式、配置全局 CSRF 策略等。

1
2
3
4
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/favicon.ico", "/robots.txt");
}

最佳实践

不要在一个类中配置所有内容。将安全配置拆分成多个类,每个类负责一个方面(认证、授权、CSRF 等)。

使用 PasswordEncoder Bean。不要硬编码密码,始终使用 BCrypt 或其他安全的密码编码器。

遵循最小权限原则。默认拒绝所有访问,只开放必要的公开接口。