Spring Security工作原理

本文介绍了SpringSecurity的初始化过程,重点解析了SpringSecurityFilterChain和其内部的过滤器,包括SecurityContextPersistenceFilter、UsernamePasswordAuthenticationFilter、ExceptionTranslationFilter以及FilterSecurityInterceptor的工作机制。还详细阐述了认证流程,如AuthenticationManager、AuthenticationProvider、UserDetailsService和PasswordEncoder的角色,以及授权流程中的FilterSecurityInterceptor、AccessDecisionManager和AccessDecisionVoter的决策过程。
摘要由CSDN通过智能技术生成

第一次尝试认真专研框架的工作原理,和了解其源码。很难啃,但回味无穷,很有意思。
更多笔记详情欢迎访问:https://gitee.com/xie-linghong/typora-notes

Spring Security工作原理

  • 当初始化Spring Security时,会创建一个名为 SpringSecurityFilterChain 的Servlet过滤器,类型为 org.springframework.security.web.FilterChainProxy,它实现了javax.servlet.Filter,因此外部的请求会经过此类。
    在这里插入图片描述

  • FilterChainProxy是一个代理,真正起作用的是FilterChainProxy中SecurityFilterChain所包含的各个Filter,同时 这些Filter作为Bean被Spring管理,它们是Spring Security核心,各有各的职责,但他们并不直接处理用户的认 证,也不直接处理用户的授权,而是把它们交给了认证管理器(AuthenticationManager)和决策管理器 (AccessDecisionManager)进行处理。

在这里插入图片描述

  • SecurityContextPersistenceFilter:这个Filter是整个拦截过程的入口和出口(也就是第一个和最后一个拦截 器),会在请求开始时从配置好的 SecurityContextRepository 中获取 SecurityContext,然后把它设置给 SecurityContextHolder。在请求完成后将 SecurityContextHolder 持有的 SecurityContext 再保存到配置好 的 SecurityContextRepository,同时清除 securityContextHolder 所持有的 SecurityContext;
  • *UsernamePasswordAuthenticationFilter: 用于处理来自表单提交的认证。该表单必须提供对应的用户名和密 码,其内部还有登录成功或失败后进行处理的 AuthenticationSuccessHandler 和 AuthenticationFailureHandler,这些都可以根据需求做相关改变;
  • ExceptionTranslationFilter: 能够捕获来自 FilterChain 所有的异常,并进行处理。但是它只会处理两类异常: AuthenticationException 和 AccessDeniedException,其它的异常它会继续抛出。
  • *FilterSecurityInterceptor: 是用于保护web资源的,使用AccessDecisionManager对当前用户进行授权访问。
认证流程 UsernamePasswordAuthenticationFilter

在这里插入图片描述

  • AuthenticationManager

    1. 认证相关的核心接口,也是发起认证的出发点,它的实现类为ProviderManager
    2. Spring Security支持多种认证方式,因此ProviderManager维护着一个 List<AuthenticationProvider>列表,存放多种认证方式,最终实际的认证工作是由 AuthenticationProvider完成的。
    3. web表单对应的AuthenticationProvider实现类为 DaoAuthenticationProvider,它的内部又维护着一个UserDetailsService负责UserDetails的获取。最终 AuthenticationProviderUserDetails填充至Authentication

在这里插入图片描述

  • AuthenticationProvider:认证管理器(AuthenticationManager)委托 AuthenticationProvider完成认证工作。AuthenticationProvider是一个接口:

    public interface AuthenticationProvider {
    	Authentication authenticate(Authentication authentication) throws AuthenticationException;
    	boolean supports(Class<?> var1);
    }
    
    1. **authenticate()**方法定义了认证的实现过程,它的参数是一个Authentication,里面包含了登录用户所提交的用 户、密码等。而返回值也是一个Authentication,这个Authentication则是在认证成功后,将用户的权限及其他信 息重新组装后生成。

    2. ProviderManager维护着一个 List<AuthenticationProvider>列表,存放多种认证方式,不同的认证方式使用不同的AuthenticationProvider。如:用户名密码、短信……

    3. 每个AuthenticationProvider需要实现supports()方法来表明自己支持的认证方式,例如:我们使用表单方式认证, 在提交请求时Spring Security会生成UsernamePasswordAuthenticationToken,它是一个Authentication,里面 封装着用户提交的用户名、密码信息,而对应的就会由DaoAuthenticationProvider处理。因为DaoAuthenticationProvider的实现如下:

      public boolean supports(Class<?> authentication) {
      	return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
      }
      
    • UserDetailsService

      1. DaoAuthenticationProvider中包含了一个UserDetailsService实例

      2. UserDetailsService负责根据用户名提取数据库或者内存中的用户信息 UserDetails(包含密码)

      3. 而后DaoAuthenticationProvider会去对比UserDetailsService提取的用户密码与用户提交 的密码是否匹配作为认证成功的关键依据

      4. 可以通过将自定义的 UserDetailsService 公开为spring bean来定义自定义身份验证。

        @Service
        public class SpringDataUserDetailsService implements UserDetailsService {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException 	{
                // 如果是数据库,直接查询到对象后,将下面的参数改成对象的属性即可
                UserDetails userDetails = User.withUsername(username).password("123").authorities("p1").build();
                return userDetails;
            }
        }
        
      5. InMemoryUserDetailsManager(内存认证),JdbcUserDetailsManager(jdbc认证)就是 UserDetailsService的实现类,主要区别无非就是从内存还是从数据库加载用户。

        @Bean
        public UserDetailsService userDetailsService() {
            InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
            manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build());
            manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build());
            return manager;
        }
        
      • UserDetailsService只负责从特定 的地方(通常是数据库)加载用户信息,仅此而已。
      • DaoAuthenticationProvider的职责更大,它完成完整的认证流程,同时会把UserDetails填充至Authentication
      public interface UserDetailsService {
      	UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
      }
      
    • PasswordEncoder

      1. DaoAuthenticationProvider认证处理器通过UserDetailsService获取到UserDetails

      2. DaoAuthenticationProvider通过 PasswordEncoder接口的matches方法进行密码的对比,而具体的密码对比细节取决于实现。

        public interface PasswordEncoder {
            String encode(CharSequence var1);
            boolean matches(CharSequence var1, String var2);
            default boolean upgradeEncoding(String encodedPassword) {
            	return false;
            }
        }
        
      3. Spring Security提供很多内置的PasswordEncoder实现:

        1. BCryptPasswordEncoder:每次加密后的密码不一样,但都可与明文密码配对成功

          BCrypt.hashpw(“明文密码”,BCrypt.gensalt()):返回明文密码加盐后的加密密码值

          BCrypt.checkpw(“明文密码”, “加密密码”):判断密码是否一致

        2. Pbkdf2PasswordEncoder

        3. SCryptPasswordEncoder

        4. NoOpPasswordEncoder:不适用任何加密处理

        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        	// return NoOpPasswordEncoder.getInstance();
        }
        
  • Authentication(认证信息),它是一个接口,UsernamePasswordAuthenticationToken就是它的实现之一。

    // Authentication 是 spring security 包中的接口,直接继承自Principal类,而 Principal 是位于 java.security 包中的。它是表示着一个抽象主体身份,任何主体都有一个名称,因此包含一个getName()方法。
    public interface Authentication extends Principal, Serializable { 
        
        // getAuthorities(),权限信息列表,默认是GrantedAuthority接口的一些实现类,通常是代表权限信息的一系列字符串。
    	Collection<? extends GrantedAuthority> getAuthorities(); 
        
        // getCredentials(),凭证信息,用户输入的密码字符串,在认证过后通常会被移除,用于保障安全。
        Object getCredentials(); 
        
        // getDetails(),详细信息,通常是一个UserDetails对象,其中包含了用户的详细信息
        Object getDetails(); 
        
        // getPrincipal(),身份信息,是用于标识和识别用户的身份信息。大部分情况下返回的是UserDetails接口的实现类,UserDetails代表用户的详细信息。
        Object getPrincipal(); 
        
        boolean isAuthenticated();
        void setAuthenticated(boolean var1) throws IllegalArgumentException;
    }
    
    
    • UserDetails

      1. DaoAuthenticationProvider处理了web表单的认证逻辑,认证成功后既得到一个 Authentication(UsernamePasswordAuthenticationToken实现)。
      2. Authentication里面包含了身份信息(Principal)。这个身份信息就是一个 Object ,大多数情况下它可以被强转为UserDetails对象。
      3. Authentication的**getCredentials()UserDetails中的getPassword()**需要被区分对待,前者是用户提交的密码凭证,后者是用户实际存储的密码,认证其实就是对这两者的比对。
      4. Authentication中的getAuthorities()实际是由UserDetails的**getAuthorities()**传递而形成的。
      5. AuthenticationgetDetails()方法是由UserDetails经过了 AuthenticationProvider认证之后被UserDetails填充的。
      public interface UserDetails extends Serializable {
          Collection<? extends GrantedAuthority> getAuthorities();
          String getPassword();
          String getUsername();
          boolean isAccountNonExpired();
          boolean isAccountNonLocked();
          boolean isCredentialsNonExpired();
          boolean isEnabled();
      }
      
授权流程 FilterSecurityInterceptor

在这里插入图片描述

  1. FilterSecurityInterceptor会从 SecurityMetadataSource 的子类 DefaultFilterInvocationSecurityMetadataSource 获取要访问当前资源所需要的权限 Collection<ConfigAttribute>

  2. SecurityMetadataSource其实就是读取访问策略的抽象,而读取的内容,其实就是我们配置的访问规则

    http
    .authorizeRequests()
    .antMatchers("/r/r1").hasAuthority("p1")
    .antMatchers("/r/r2").hasAuthority("p2")
    ...
    
  3. FilterSecurityInterceptor会调用 AccessDecisionManager 进行授权决策,若决策通过,则允许访问资 源,否则将禁止访问。AccessDecisionManager(访问决策管理器)的核心接口如下:

    public interface AccessDecisionManager {
        // decide接口就是用来鉴定当前用户是否有访问对应受保护资源的权限。
    
        // authentication:要访问资源的访问者的身份
        // object:要访问的受保护资源,web请求对应FilterInvocation
        // configAttributes:是受保护资源的访问策略,通过SecurityMetadataSource获取。
        void decide(Authentication authentication , Object object, Collection<ConfigAttribute>
        configAttributes ) throws AccessDeniedException, InsufficientAuthenticationException;
        //略..
    }
    
    • 授权决策:AccessDecisionManager采用投票的方式来确定是否能够访问受保护资源。AccessDecisionManager中包含的一系列AccessDecisionVoter将会被用来对Authentication 是否有权访问受保护对象进行投票,AccessDecisionManager根据投票结果,做出最终决策。
      在这里插入图片描述

      public interface AccessDecisionVoter<S> {
          int ACCESS_GRANTED = 1; // 同意
          int ACCESS_ABSTAIN = 0; // 弃权
          int ACCESS_DENIED =1; // 拒绝
          boolean supports(ConfigAttribute var1);
          boolean supports(Class<?> var1);
          // vote()方法的返回结果会是AccessDecisionVoter中定义的三个常量之一
          // 如果一个AccessDecisionVoter不能判定当前Authentication是否拥有访问对应受保护对象的权限,则其vote()方法的返回值应当为弃权ACCESS_ABSTAIN
          int vote(Authentication var1, S var2, Collection<ConfigAttribute> var3);
      }
      
      • Spring Security内置了三个基于投票的AccessDecisionManager实现类
        • AffirmativeBased
          (1)只要有AccessDecisionVoter的投票为ACCESS_GRANTED则同意用户进行访问;
          (2)如果全部弃权也表示通过;
          (3)如果没有一个人投赞成票,但是有人投反对票,则将抛出AccessDeniedException。
          (4) Spring security默认使用的是AffirmativeBased。
        • ConsensusBased
          (1)如果赞成票多于反对票则表示通过。
          (2)反过来,如果反对票多于赞成票则将抛出AccessDeniedException。
          (3)如果赞成票与反对票相同且不等于0,并且属性allowIfEqualGrantedDeniedDecisions的值为true,则表示通过,否则将抛出异常AccessDeniedException。参数allowIfEqualGrantedDeniedDecisions的值默认为true
          (4)如果所有的AccessDecisionVoter都弃权了,则将视参数allowIfAllAbstainDecisions的值而定,如果该值 为true则表示通过,否则将抛出异常AccessDeniedException。参数allowIfAllAbstainDecisions的值默认为false
        • UnanimousBased
          (1)如果受保护对象配置的某一个ConfigAttribute被任意的AccessDecisionVoter反对了,则将抛出 AccessDeniedException。
          (2)如果没有反对票,但是有赞成票,则表示通过。
          (3)如果全部弃权了,则将视参数allowIfAllAbstainDecisions的值而定,true则通过,false则抛出 AccessDeniedException。参数allowIfAllAbstainDecisions的值默认为false
        • 三者区别:
          前两种会一次性把受保护对象的配置属性全部传递 给AccessDecisionVoter进行投票;而UnanimousBased会一次只传递一个ConfigAttribute给 AccessDecisionVoter进行投票。
      • Spring Security也内置一些投票者实现类。如:RoleVoter、AuthenticatedVoter和WebExpressionVoter等
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值