Spring Security 通过其核心组件 SecurityContextHolder 管理认证信息的存储和访问。
认证信息存储的组件结构:
- SecurityContextHolder:作为安全上下文的持有者,默认使用 ThreadLocal 存储当前线程的 SecurityContext,确保不同线程间的上下文隔离。
- SecurityContext:包含当前用户的认证信息,核心属性为 Authentication 对象。
- Authentication:封装用户的身份凭证(如用户名、密码)、权限列表(GrantedAuthority)等详细信息。
1、将认证信息存入安全上下文
//获取权限列表
List<GrantedAuthority> grantedAuthorityList = AuthorityUtils.commaSeparatedStringToAuthorityList("staff:list,staff:add,staff:delete");
//初始化 UserDetails 登录对象
UserDetails user = new User(
accountCode, //用户名称
password, //用户密码
true, //是否启用
true, true, true, //其它状态
grantedAuthorityList); //权限列表
Authentication authentication = new UsernamePasswordAuthenticationToken(user, accessToken, grantedAuthorityList);
// 将认证信息存入安全上下文
SecurityContextHolder.getContext().setAuthentication(authentication);
2、清除 Spring Security 认证信息
// 清除 Spring Security 认证信息
SecurityContextHolder.clearContext();