码迷,mamicode.com
首页 > 编程语言 > 详细

串理spring security认证流程源码

时间:2018-12-26 23:02:40      阅读:313      评论:0      收藏:0      [点我收藏+]

标签:get   hide   type   ret   之间   cep   传递   ati   .class   

1.认证流程流程
技术分享图片
通过断点调试,可以看到在UsernamepasswordAuthenticationFilter中构造了一个
UsernamePasswordAuthenticationToken对象

技术分享图片
打开UsernamePasswordAuthenticationToken可得知,该实现类是Authentication的子类,因为Authentication是封装了用户的信息。
在该构造函数中,其中super(null)是调用了父类的方法
技术分享图片
父类的方法如下:

    public AbstractAuthenticationToken(Collection<? extends GrantedAuthority> authorities) {
        if (authorities == null) { //为空时,需要赋个默认的权限,因为此时还未进行身份认证
            this.authorities = AuthorityUtils.NO_AUTHORITIES;   
            return;
        }

        for (GrantedAuthority a : authorities) {
            if (a == null) {
                throw new IllegalArgumentException(
                        "Authorities collection cannot contain any null elements");
            }
        }
        ArrayList<GrantedAuthority> temp = new ArrayList<GrantedAuthority>(
                authorities.size());
        temp.addAll(authorities);
        this.authorities = Collections.unmodifiableList(temp);
    }

setAuthenticated(false) 代表当前存进去的principal/credentials是否经过身份认证,此时肯定是没有的。

setDetails(request, authRequest);

该方法会把请求的一些信息设置到UsernamePasswordAuthenticationToken里面去,包括当前发起请求的IP,Session等

return this.getAuthenticationManager().authenticate(authRequest); //往AuthenticationManager靠拢

AuthenticationManager该类本身不包含校验的逻辑,它的作用是用来管理AuthenticationProvider
该方法会请求进入:ProviderManager.authenticate()方法,该类实现了AuthenticationManager接口

public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
        Class<? extends Authentication> toTest = authentication.getClass();
        AuthenticationException lastException = null;
        Authentication result = null;
        boolean debug = logger.isDebugEnabled();

        for (AuthenticationProvider provider : getProviders()) { //
            if (!provider.supports(toTest)) {
                continue;
            }
            /*
            getProviders() 拿到所有的AuthenticationProvider,校验逻辑都是在Provider中
            因为不同的登录方式,它的认证逻辑是不通 的,目前使用的用户名+密码的方式,后续还会有第三方登录,手机    号验证码登录等,provider.supports(toTest)是否支持当前的登录方式(判断)
            对于用户名密码方式,它传递的token是:UsernamePasswordAuthenticationToken,而对于第三方登录时的验证方式则是SocialAuthenticationToken
            */

            if (debug) {
                logger.debug("Authentication attempt using "
                        + provider.getClass().getName());
            }

            try {
            //具体执行校验逻辑
                result = provider.authenticate(authentication);

                if (result != null) {
                    copyDetails(authentication, result);
                    break;
                }
            }
            catch (AccountStatusException e) {
                prepareException(e, authentication);
                throw e;
            }
            catch (InternalAuthenticationServiceException e) {
                prepareException(e, authentication);
                throw e;
            }
            catch (AuthenticationException e) {
                lastException = e;
            }
        }

        if (result == null && parent != null) {
            // Allow the parent to try.
            try {
                result = parent.authenticate(authentication);
            }
            catch (ProviderNotFoundException e) {
            }
            catch (AuthenticationException e) {
                lastException = e;
            }
        }

        if (result != null) {
            if (eraseCredentialsAfterAuthentication
                    && (result instanceof CredentialsContainer)) {
                ((CredentialsContainer) result).eraseCredentials();
            }

            eventPublisher.publishAuthenticationSuccess(result);
            return result;
        }

        if (lastException == null) {
            lastException = new ProviderNotFoundException(messages.getMessage(
                    "ProviderManager.providerNotFound",
                    new Object[] { toTest.getName() },
                    "No AuthenticationProvider found for {0}"));
        }

        prepareException(lastException, authentication);

        throw lastException;
    }

provider.authenticate()实现类是写在AuthenticationProvider的实现类AbstractUserDetailsAuthenticationProvider中

public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
        Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
                messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.onlySupports",
                        "Only UsernamePasswordAuthenticationToken is supported"));

        String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
                : authentication.getName();

        boolean cacheWasUsed = true;
        UserDetails user = this.userCache.getUserFromCache(username);

        if (user == null) {
            cacheWasUsed = false;

            try {
            //获取用户信息,具体实现类在:DaoAuthenticationProvider.retrieveUser()
                user = retrieveUser(username,
                        (UsernamePasswordAuthenticationToken) authentication);
            }
            catch (UsernameNotFoundException notFound) {
                logger.debug("User ‘" + username + "‘ not found");

                if (hideUserNotFoundExceptions) {
                    throw new BadCredentialsException(messages.getMessage(
                            "AbstractUserDetailsAuthenticationProvider.badCredentials",
                            "Bad credentials"));
                }
                else {
                    throw notFound;
                }
            }

            Assert.notNull(user,
                    "retrieveUser returned null - a violation of the interface contract");
        }

        try {
            preAuthenticationChecks.check(user);
            additionalAuthenticationChecks(user,
                    (UsernamePasswordAuthenticationToken) authentication);
        }
        catch (AuthenticationException exception) {
            if (cacheWasUsed) {
                cacheWasUsed = false;
                user = retrieveUser(username,
                        (UsernamePasswordAuthenticationToken) authentication);
                preAuthenticationChecks.check(user);
                additionalAuthenticationChecks(user,
                        (UsernamePasswordAuthenticationToken) authentication);
            }
            else {
                throw exception;
            }
        }

        postAuthenticationChecks.check(user);

        if (!cacheWasUsed) {
            this.userCache.putUserInCache(user);
        }

        Object principalToReturn = user;

        if (forcePrincipalAsString) {
            principalToReturn = user.getUsername();
        }

        return createSuccessAuthentication(principalToReturn, authentication, user);
    }
    protected final UserDetails retrieveUser(String username,
            UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException {
        UserDetails loadedUser;

        try {
            loadedUser = this.getUserDetailsService().loadUserByUsername(username);
            /**
            getUserDetailService在调用我们提供的UserDetailService的实现,也就是:MyUserDetailsService

            */
        }
        catch (UsernameNotFoundException notFound) {
            if (authentication.getCredentials() != null) {
                String presentedPassword = authentication.getCredentials().toString();
                passwordEncoder.isPasswordValid(userNotFoundEncodedPassword,
                        presentedPassword, null);
            }
            throw notFound;
        }
        catch (Exception repositoryProblem) {
            throw new InternalAuthenticationServiceException(
                    repositoryProblem.getMessage(), repositoryProblem);
        }

        if (loadedUser == null) {
            throw new InternalAuthenticationServiceException(
                    "UserDetailsService returned null, which is an interface contract violation");
        }
        return loadedUser;
    }

拿到用户信息之后,回到AbstractUserDetailsAuthenticationProvider

try {
            preAuthenticationChecks.check(user);
            additionalAuthenticationChecks(user,
                    (UsernamePasswordAuthenticationToken) authentication);
                    //在dao里校验密码是否匹配
        }

它会预检查用户是否过期,是否禁用,之后检查密码是否匹配。
预检查之后还会有后置检查

postAuthenticationChecks.check(user);  //

所有检查都通过,就会认为用户的认证是成功的。

return createSuccessAuthentication(principalToReturn, authentication, user);

protected Authentication createSuccessAuthentication(Object principal,
            Authentication authentication, UserDetails user) {
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
                principal, authentication.getCredentials(),
                authoritiesMapper.mapAuthorities(user.getAuthorities()));
        result.setDetails(authentication.getDetails());

        return result;
    }

再次new 了UsernamePasswordAuthenticationToken对象,区别再与构造方法不同,传递的参数不同,这个时候权限,用户信息都已经拿到
技术分享图片

2.认证结果如何在多个请求之间共享

3.获取用户认证的信息

串理spring security认证流程源码

标签:get   hide   type   ret   之间   cep   传递   ati   .class   

原文地址:http://blog.51cto.com/mazongfei/2335750

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!