Spring Security 教程(07)、HttpSecurity

HttpSecurity:安全配置的入口

Spring Security 配图
Spring Security 配图
Spring Security 配图

HttpSecurity 是 Spring Security 配置的核心入口。通过它,你可以对每个 HTTP 请求应用细粒度的安全策略。

基础请求授权

1
2
3
4
5
6
http.authorizeRequests()
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/api/users/**").hasAuthority("USER_READ")
.requestMatchers(HttpMethod.POST, "/api/orders/**").hasRole("ADMIN")
.anyRequest().authenticated();

关键要点:

  • 匹配顺序很重要:Spring Security 从上到下匹配,第一个匹配的规则生效。所以具体规则要放在前面,通配规则放在后面。
  • anyRequest() 是兜底:必须放在最后,确保所有请求都有安全策略。
  • permitAll() 不需要认证:任何人(包括未登录用户)都可以访问。
  • authenticated() 需要认证:用户必须登录才能访问。

异常处理

1
2
3
http.exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
.accessDeniedHandler(new CustomAccessDeniedHandler());

authenticationEntryPoint 处理未认证用户的异常,默认行为是重定向到登录页。
accessDeniedHandler 处理已认证但无权限的异常,默认行为是返回 403。

CSRF 配置

1
2
3
http.csrf()
.csrfTokenRepository(CsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers("/api/**");

对于前后端分离的应用,通常需要关闭 CSRF 防护(API 使用 JWT 等无状态认证时):

1
http.csrf().disable();

会话管理

1
2
3
http.sessionManagement()
.maximumSessions(1) // 同一用户最多 1 个会话
.maxSessionsPreventsLogin(true); // 超出限制时拒绝新登录

可以防止同一个账号在多台设备同时登录,或者控制并发会话数量。

请求缓存

httpsecurity 配图
httpsecurity 配图
httpsecurity 配图

当用户访问受保护资源但尚未认证时,Spring Security 会将原始请求保存到 RequestCache 中。认证成功后,自动重定向到原始请求的 URL。

这是为什么你在登录成功后会自动跳转到之前访问的页面——即使你直接访问了 /admin/dashboard,登录后也会自动跳转过去。