美文网首页
SpringSecurity源码解析-AbstractAuthe

SpringSecurity源码解析-AbstractAuthe

作者: 圆滚滚_8e70 | 来源:发表于2018-12-05 23:41 被阅读0次

    package org.springframework.security.web.authentication

    类图-总体结构

    AbstractAuthenticationProcessingFilter类图

    类图说明

    从类图上看AbstractAuthenticationProcessingFilter这个类继承了GenericFilterBean,以及实现了MessageSourceAwareApplicationEventPublisherAware俩个接口。

    GenericFilterBean相关内容见[源码解析-GenericFilterBean]

    说明

    从命名上看,AbstractAuthenticationProcessingFilter这个类是一个抽象类。抽象类的话应该是抽象了某一部分逻辑。下面我们来看看具体抽象了什么逻辑。

    构造方法

    1.protected AbstractAuthenticationProcessingFilter(String)

    • 构造方法说明
      根据输入的字符串创建一个实例
    • 入参
      String defaultFilterProcesssUrl 默认过滤器处理URL
    • 源码解析
    /**
         * @param defaultFilterProcessesUrl the default value for <tt>filterProcessesUrl</tt>.
         */
        protected AbstractAuthenticationProcessingFilter(String defaultFilterProcessesUrl) {
            //调用了setFilterProcessesUrl方法,设置过滤器处理的URL
            setFilterProcessesUrl(defaultFilterProcessesUrl);
        }
    

    2.protected AbstractAuthenticationProcessingFilter(RequestMatcher)

    • 构造方法说明
      根据输入的RequestMatcher对象创建一个实例
    • 入参
      RequestMatcher URL请求匹配器
    • 源码解析
    /**
         * Creates a new instance
         *
         * @param requiresAuthenticationRequestMatcher the {@link RequestMatcher} used to
         * determine if authentication is required. Cannot be null.
         */
        protected AbstractAuthenticationProcessingFilter(
                RequestMatcher requiresAuthenticationRequestMatcher) {
            Assert.notNull(requiresAuthenticationRequestMatcher,
                    "requiresAuthenticationRequestMatcher cannot be null");
            //设置requiresAuthenticationRequestMatcher属性
            this.requiresAuthenticationRequestMatcher = requiresAuthenticationRequestMatcher;
        }
    

    实例方法

    1.public void afterPropertiesSet()

    • 方法说明
      实例初始化的时候会被调用该方法
    • 入参
    • 出参
    • 源码解析
    @Override
        public void afterPropertiesSet() {
            // 断言authenticationManager不为空
            Assert.notNull(authenticationManager, "authenticationManager must be specified");
        }
    

    2.public void doFilter(ServletRequest,ServletResponse,FilterChain)throws IOException, ServletException

    • 方法说明
      主要是用于决定请求是否需要被该过滤器拦截,并且进行认证处理
    • 入参
      ServletRequsetHTTP请求
      ServletResponseHTTP返回
      FilterChain过滤链
    • 出参
    • 抛出异常
      IOExceptionIO类异常
      ServletExceptionServlet异常
    • 源码解析
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
                throws IOException, ServletException {
    
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
    
            if (!requiresAuthentication(request, response)) {
                chain.doFilter(request, response);
    
                return;
            }
    
            if (logger.isDebugEnabled()) {
                logger.debug("Request is to process authentication");
            }
    
            Authentication authResult;
    
            try {
                authResult = attemptAuthentication(request, response);
                if (authResult == null) {
                    // return immediately as subclass has indicated that it hasn't completed
                    // authentication
                    return;
                }
                sessionStrategy.onAuthentication(authResult, request, response);
            }
            catch (InternalAuthenticationServiceException failed) {
                logger.error(
                        "An internal error occurred while trying to authenticate the user.",
                        failed);
                unsuccessfulAuthentication(request, response, failed);
    
                return;
            }
            catch (AuthenticationException failed) {
                // Authentication failed
                unsuccessfulAuthentication(request, response, failed);
    
                return;
            }
    
            // Authentication success
            if (continueChainBeforeSuccessfulAuthentication) {
                chain.doFilter(request, response);
            }
    
            successfulAuthentication(request, response, chain, authResult);
        }
    
    • 程序流程图


      doFilter程序流程图

    3.protected boolean requireAuthentication(HttpServletRequest,HttpServletResponse)

    • 方法说明
      判断request是否需要进行认证
    • 入参
      HttpServletRequest HTTP请求
      HttpServletResponse HTTP返回
    • 出参
      boolean 如果true表示需要认证;如果false表示不需要认证。
    • 源码分析
    /**
         * Indicates whether this filter should attempt to process a login request for the
         * current invocation.
         * <p>
         * It strips any parameters from the "path" section of the request URL (such as the
         * jsessionid parameter in <em>http://host/myapp/index.html;jsessionid=blah</em>)
         * before matching against the <code>filterProcessesUrl</code> property.
         * <p>
         * Subclasses may override for special requirements, such as Tapestry integration.
         *
         * @return <code>true</code> if the filter should attempt authentication,
         * <code>false</code> otherwise.
         */
        protected boolean requiresAuthentication(HttpServletRequest request,
                HttpServletResponse response) {
            //判断request是否满足requiresAuthenticationRequestMatcher的要求
            return requiresAuthenticationRequestMatcher.matches(request);
        }
    

    4.public abstract Authentication attemptAuthentication(HttpServletRequest,HttpServletResponse) throws AuthenticationException,IOException,ServletException

    • 方法说明
      尝试进行认证,抽象方法,便于子类实现。
    • 入参
      HttpServletRequest请求request
      HttpServletResponse请求response
    • 出参
      Authentication认证结果。
    • 抛出异常
      AuthenticationException 认证异常
      IOException IO异常
      ServletException Servlet异常
    • 源码解析
    public abstract Authentication attemptAuthentication(HttpServletRequest request,
                HttpServletResponse response) throws AuthenticationException, IOException,
                ServletException;
    

    5.protected void successfulAuthentication(HttpServletRequest,HttpServletResponse,FilterChain,Authentication) throws IOException,ServletException

    • 方法说明
      认证成功后的默认操作
    • 入参
      HttpServletRequest http请求体
      HttpServletResponse http返回结果
      FilterChain过滤器链
      Authentication 认证信息
    • 出参
    • 抛出异常
      IOException IO异常
      ServletExceptionServlet异常
    • 源码解析
    protected void successfulAuthentication(HttpServletRequest request,
                HttpServletResponse response, FilterChain chain, Authentication authResult)
                throws IOException, ServletException {
    
            if (logger.isDebugEnabled()) {
                logger.debug("Authentication success. Updating SecurityContextHolder to contain: "
                        + authResult);
            }
    
            //将认证结果存储到SecurityContext中
            SecurityContextHolder.getContext().setAuthentication(authResult);
    
            //登录成功处理
            rememberMeServices.loginSuccess(request, response, authResult);
    
            //如果时间发布不为空
            // Fire event
            if (this.eventPublisher != null) {
              //发布认证成功事件
                eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
                        authResult, this.getClass()));
            }
    
            //认证成功拦截器处理
            successHandler.onAuthenticationSuccess(request, response, authResult);
        }
    

    6.protected void unsuccessfulAuthentication(HttpServletRequest,HttpServletResponse,AuthenticationException) throws IOException, ServletException

    • 方法说明
      认证失败后的默认操作
    • 入参
      HttpServletRequestHTTP请求体
      HttpServletResponseHTTP返回结果
      AuthenticationException认证异常
    • 出参
    • 抛出异常
      IOExceptionIO异常
      ServletExceptionServlet异常
    • 源码分析
    /**
         * Default behaviour for unsuccessful authentication.
         * <ol>
         * <li>Clears the {@link SecurityContextHolder}</li>
         * <li>Stores the exception in the session (if it exists or
         * <tt>allowSesssionCreation</tt> is set to <tt>true</tt>)</li>
         * <li>Informs the configured <tt>RememberMeServices</tt> of the failed login</li>
         * <li>Delegates additional behaviour to the {@link AuthenticationFailureHandler}.</li>
         * </ol>
         */
        protected void unsuccessfulAuthentication(HttpServletRequest request,
                HttpServletResponse response, AuthenticationException failed)
                throws IOException, ServletException {
    
            //清理SecurityContext上下文
            SecurityContextHolder.clearContext();
    
            if (logger.isDebugEnabled()) {
                logger.debug("Authentication request failed: " + failed.toString(), failed);
                logger.debug("Updated SecurityContextHolder to contain null Authentication");
                logger.debug("Delegating to authentication failure handler " + failureHandler);
            }
    
            //登录失败处理
            rememberMeServices.loginFail(request, response);
    
            //认证失败拦截器处理
            failureHandler.onAuthenticationFailure(request, response, failed);
        }
    

    7.protected AuthenticationManager getAuthenticationManager()

    • 方法说明
      获取认证管理服务
    • 入参
    • 出参
      AuthenticationManager认证管理服务
    • 源码解析
    protected AuthenticationManager getAuthenticationManager() {
            return authenticationManager;
        }
    

    8.public void setAuthenticationManager(AuthenticationManger)

    • 方法说明
      设置认证管理服务
    • 入参
      AuthenticationManager认证管理服务
    • 出参
    • 源码解析
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
            this.authenticationManager = authenticationManager;
        }
    

    9.public void setFilterProcessesUrl(String)

    • 方法说明
      设置URL用来判断请求是否需要认证
    • 入参
      StringfilterProcessesUrl
    • 出参
    • 源码解析
    /**
         * Sets the URL that determines if authentication is required
         *
         * @param filterProcessesUrl
         */
        public void setFilterProcessesUrl(String filterProcessesUrl) {
            //设置需要认证的认证请求匹配器
            //默认为AntPathRequestMatcher
            setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(
                    filterProcessesUrl));
        }
    

    10.public final void setRequiresAuthenticationRequestMatcher(RequestMatcher)

    • 方法说明
      设置请求匹配器
    • 入参
      RequestMatcher 请求匹配器
    • 出参
    • 源码解析
    public final void setRequiresAuthenticationRequestMatcher(
                RequestMatcher requestMatcher) {
            Assert.notNull(requestMatcher, "requestMatcher cannot be null");
            this.requiresAuthenticationRequestMatcher = requestMatcher;
        }
    

    11.public RememberMeServices getRememberMeServices()

    • 方法说明
      获取rememberMeServices服务,默认是NullRememberMeServices
    • 入参
    • 出参
      RememberMeServices实例
    • 源码解析
    public RememberMeServices getRememberMeServices() {
            return rememberMeServices;
        }
    

    12.public void setRememberServices(RememberMeServices)

    • 方法说明
      设置rememberMeServices
    • 入参
      rememberMeServices 实例
    • 出参
    • 源码解析
    public void setRememberMeServices(RememberMeServices rememberMeServices) {
            Assert.notNull(rememberMeServices, "rememberMeServices cannot be null");
            this.rememberMeServices = rememberMeServices;
        }
    

    13.其他属性的getter和setter方法

    相关文章

      网友评论

          本文标题:SpringSecurity源码解析-AbstractAuthe

          本文链接:https://www.haomeiwen.com/subject/ndtgcqtx.html