认证控制
springsecurity 的认证过程的处理是通过过滤器进行拦截处理的,在请求前判断是否有具体的权限来做一些控制;
基本流程是通过过滤器 拿到请求信息,交给访问决策管理器(AccessDecisionManager) 判断是否有权限,
而 访问决策管理器(AccessDecisionManager) 通过投票机制判断是否有权限,对应的实现类聚合了多个 AccessDecisionVoter (访问投票器),
对于一个请求 所有的投票器可以投出自己的一票 通过 ,拒绝 或弃权,根据投票的最终结果得出是否允许访问成功;
首先先认识几个重要的组件;
访问决策管理器 (AccessDecisionManager)
AccessDecisionManager 来处理关于访问的判断控制,在过滤器拦截后 会交给此管理器来判断是否有访问权限
核心方法是 decide 方法;
对应的实现类管理了多个 AccessDecisionVoter (访问投票器) 由多个投票器进行投票;
AbstractAccessDecisionManager
AbstractAccessDecisionManager 是公共的抽象实现,封装了公共逻辑
针对不同的投票如何处理有3个处理类;
- AffirmativeBased 任何一个投票者 通过即为通过
- UnanimousBased 必须所有的投票者全部通过
- ConsensusBased 多数的投票者通过即为通过
void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
throws AccessDeniedException, InsufficientAuthenticationException;
boolean supports(ConfigAttribute attribute);
boolean supports(Class<?> clazz);
访问投票器 AccessDecisionVoter
根据当前请求和权限信息决定是否通过,拒绝或弃权;
int ACCESS_GRANTED = 1;
int ACCESS_ABSTAIN = 0;
int ACCESS_DENIED = -1;
有多个实现类处理不同的权限投票逻辑;
- RoleVoter 基于角色的投票
- WebExpressionVoter 表达式的投票
- RoleHierarchyVoter 继承 RoleVoter ,处理角色的层级结构返回给 RoleVoter
- AuthenticatedVoter 其主要用来区分匿名用户、通过Remember-Me认证的用户和完全认证的用户。完全认证的用户是指由系统提供的登录入口进行成功登录认证的用户。
- PreInvocationAuthorizationAdviceVoter 处理@pre 相关注解的投票认证
以RoleVoter 来说明,主要做了角色的code的比对处理返回对应的投票状态;
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
if (authentication == null) {
return ACCESS_DENIED;
}
int result = ACCESS_ABSTAIN;
Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication);
for (ConfigAttribute attribute : attributes) {
if (this.supports(attribute)) {
result = ACCESS_DENIED;
// Attempt to find a matching granted authority
for (GrantedAuthority authority : authorities) {
if (a