Spring Security 概念基础 验证流程
认证&授权
- 认证:确定是否为合法用户
- 授权:分配角色权限(分配角色,分配资源)
认证管理器(Authentication Manager)
负责认证用户是否为合法
访问决策管理器(Access Decision Manager)
负责判定一个安全实体是不是有适当的访问权限
认证
//认证 user request ↓ (AbstractClass) AbstractAuthenticationProcessingFilter |-获取用户提供个信息并创建一个部分完整的 Authentication 对象来传递凭证信息 (实现类)UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter |-do: create o.s.s.core.Authentication (生成用户信息 UsernamePasswordAuthenticationToken) ↓ (Interface) AuthenticationManager |-校验用户的凭证信息,用户无效会抛出一个特定的异常 成功会补全Authentication的信息(如权限信息) (实现类)ProviderManager implements AuthenticationManager |-注入 (interface)AuthenticationProvider |-注入 (Interface) UserDetails |-获取 o.s.s.core.userdetails.UserDetails 获取用户信息 |-验证用户是否合法,验证用户是否拥有权限 valid credentials(验证合法) /invalid credentials (用户无效)-> Throw AuthenticationException ↓ 添加其他信息如权限 (o.s.s.core.GrantedAuthority) ↓ 验证成功
o.s.s.core.Authentication(用户信息)
- 它存储安全实体的标识、密码以及认证请求的上下文信息。
- 它还包含用户认证后的信息 (可能会包含一个 UserDetails 的实例)。
- 通常不会被扩展,除非是为了支持某种特定类型的认证。
//返回安全实体的唯一标识(如,一个用户名) Object getPrincipal() //返回安全实体的凭证信息 Object getCredentials() //得到安全实体的权限集合,根据认证信息的存储决定的。 List<GrantedAuthority> getAuthorities() //返回一个跟认证相关的安全实体细节信息 Object getDetails()
UserDetails
- 为了存储一个安全实体的概况信息,包含名字、e-mail、电话号码等。
- 通常会被扩展以支持业务需求。
o.s.s.core.GrantedAuthority(权限集合)
//返回安全实体的唯一标识(如,一个用户名) Object getPrincipal() //返回安全实体的凭证信息 Object getCredentials() //得到安全实体的权限集合,根据认证信息的 存储决定的。 List<GrantedAuthority> getAuthorities() //返回一个跟认证 供者相关的安全实体细节 信息 Object getDetails()
AuthenticationException(用户验证无效异常)
- authentication 存储关联认证请求的Authentication实例;
- extraInformation 根据特定的异常可以存储额外的信息。如UsernameNotFoundException 在这个域上存储了用户名。
Exception | 解析 | extraInformation |
---|---|---|
BadCredentialsException | 如国没有供用户名或者密码与认证存储中用户名对应的密码不匹配 | UserDetails |
LockedException | 如果用户的账号被发现锁定了 | UserDetails |
UsernameNotFoundException | 如果用户名不存在或者用户没有被授予的GrantedAuthority | String(包含用户名) |
授权
//访问资源(即授权管理) user request url ↓ AbstractSecurityInterceptor (委托一个AccessDecisionManager完成授权的判断) ↓(获取配置的权限信息) FilterInvocationSecurityMetadataSource ↓ AccessDecisionManager(需要获取AccessDecisionVoters) ↓ 返回决策结果
o.s.s.access.AccessDecisionManager
//判断是否支持当前的请求。 supports() //核实访问是否被允许以及请求是否能够被接受。该方法实际上没有返回值,通过抛出异常来表明对 请求访问的拒绝。 decide()
o.s.s.access.AccessDecisionVoter (投票决策器)
Grant (ACCESS_GRANTED)
投票器允许对资源的访问
Deny (ACCESS_DENIED)
投票器拒绝对资源的访问
Abstain (ACCESS_ABSTAIN)
投票器对是否能够访问做了弃权处理(即没有做出决定)。
AccessDeniedException (以下情形返回该异常)
- AuthenticationProvider 当供的凭证不合法 或用户失效、过期;
- DaoAuthenticationProvider 当访问 DAO 数据 存储时出错;
- RememberMeServices 当 remember me cookie 被篡改; 各种特定的认证类(CAS、NTLM 等)在用户 特定的场景下。
- 当配置的 Voter 投票 拒绝访问(注意这可能在任何投票场景下)