SpringSecurity源码解析-AbstractAuthe

2018-12-05  本文已影响0人  圆滚滚_8e70

package org.springframework.security.web.authentication

类图-总体结构

AbstractAuthenticationProcessingFilter类图

类图说明

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

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

说明

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

构造方法

1.protected AbstractAuthenticationProcessingFilter(String)

/**
     * @param defaultFilterProcessesUrl the default value for <tt>filterProcessesUrl</tt>.
     */
    protected AbstractAuthenticationProcessingFilter(String defaultFilterProcessesUrl) {
        //调用了setFilterProcessesUrl方法,设置过滤器处理的URL
        setFilterProcessesUrl(defaultFilterProcessesUrl);
    }

2.protected AbstractAuthenticationProcessingFilter(RequestMatcher)

/**
     * 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

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);
    }

3.protected boolean requireAuthentication(HttpServletRequest,HttpServletResponse)

/**
     * 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

public abstract Authentication attemptAuthentication(HttpServletRequest request,
            HttpServletResponse response) throws AuthenticationException, IOException,
            ServletException;

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

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

/**
     * 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()

protected AuthenticationManager getAuthenticationManager() {
        return authenticationManager;
    }

8.public void setAuthenticationManager(AuthenticationManger)

public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

9.public void setFilterProcessesUrl(String)

/**
     * 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)

public final void setRequiresAuthenticationRequestMatcher(
            RequestMatcher requestMatcher) {
        Assert.notNull(requestMatcher, "requestMatcher cannot be null");
        this.requiresAuthenticationRequestMatcher = requestMatcher;
    }

11.public RememberMeServices getRememberMeServices()

public RememberMeServices getRememberMeServices() {
        return rememberMeServices;
    }

12.public void setRememberServices(RememberMeServices)

public void setRememberMeServices(RememberMeServices rememberMeServices) {
        Assert.notNull(rememberMeServices, "rememberMeServices cannot be null");
        this.rememberMeServices = rememberMeServices;
    }

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

上一篇下一篇

猜你喜欢

热点阅读