Spring Security 是 Spring 生态中专注于安全控制的核心框架,提供了认证、授权、攻击防护等全方位能力。它以声明式安全、可插拔架构、深度集成 Spring 著称,是 Java 企业应用安全的事实标准。
Spring Security 主流程可抽象为四大核心环节:
优点 | 缺点 |
---|---|
与Spring体系无缝集成,生态丰富 | 学习曲线较陡,配置复杂 |
机制灵活,定制扩展能力极强 | 源码量大,排查难度高 |
支持主流协议(如OAuth2、JWT、LDAP等) | 默认Web为主,非Web场景需手动适配 |
社区活跃,文档详尽,安全性业界领先 | 部分模块过重,性能需按需调优 |
function doFilter(request, response, chain):
// 1. 认证
authentication = authenticateIfNecessary(request)
if authentication == null and requiresAuthentication(request):
redirectToLogin(response)
return
// 2. 授权
if !isAuthorized(authentication, request):
denyAccess(response)
return
// 3. 进入业务处理
chain.doFilter(request, response)
authenticateIfNecessary(request)
:认证入口,通常由UsernamePasswordAuthenticationFilter
等实现。
isAuthorized(authentication, request)
:授权判断,由AccessDecisionManager
等实现。
chain.doFilter(request, response)
:继续后续业务处理。以UsernamePasswordAuthenticationFilter
为例:
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
// 1. 提取账号密码
String username = obtainUsername(request);
String password = obtainPassword(request);
// 2. 构造认证Token
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
// 3. 委托AuthenticationManager认证
return this.getAuthenticationManager().authenticate(authRequest);
}
逐行注释:
速记口诀:
提账号,组Token,交管理器。
以FilterSecurityInterceptor
为例:
public void invoke(FilterInvocation fi) throws IOException, ServletException {
// 1. 获取请求需要的权限
Collection<ConfigAttribute> attributes = this.securityMetadataSource.getAttributes(fi);
// 2. 获取当前用户
Authentication authenticated = SecurityContextHolder.getContext().getAuthentication();
// 3. 决策是否有权访问
this.accessDecisionManager.decide(authenticated, fi, attributes);
// 4. 放行到下一个过滤器
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
}
逐行注释:
速记口诀:
查权限,取身份,决策器判,放行或拒。
以SecurityContextPersistenceFilter
为例:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
// 1. 从Session获取SecurityContext
SecurityContext contextBeforeChainExecution = this.repo.loadContext(new HttpRequestResponseHolder(request, response));
SecurityContextHolder.setContext(contextBeforeChainExecution);
try {
// 2. 进入后续过滤器与业务
chain.doFilter(request, response);
} finally {
// 3. 清理线程绑定的SecurityContext
SecurityContextHolder.clearContext();
}
}
逐行注释:
速记口诀:
取上下文,执业务,清上下文。
// 方法级授权
@PreAuthorize("hasRole('ADMIN') or hasAuthority('DEPT_VIEW')")
public String getDeptList() { ... }
logging.level.org.springframework.security=DEBUG
,追踪认证授权细节。spring-boot-starter-security
一键启用。spring-security-oauth2
和spring-security-oauth2-resource-server
,支持单点登录、分布式API鉴权。hasRole('ADMIN') && hasAuthority('USER_EDIT')
,支持SpEL动态表达式。Spring Security 以其过滤器链+上下文模型+可插拔Provider+声明式注解的体系,为Java应用提供了业界领先的安全保障。理解其主流程、源码细节和架构演进,不仅能应对常见安全需求,还能驾驭分布式、云原生等复杂场景。
速记口诀:
过滤链串安全,认证授权分主线;
上下文控全局,投票决策细粒管;
可插拔易扩展,云端分布亦无难。
如需某个源码模块的逐行注释、特定业务集成案例,或更深的算法解析,欢迎留言交流!