前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Security实战-认证核心验证器验证逻辑AuthenticationProviderManagerAuthenticationProvider

Spring Security实战-认证核心验证器验证逻辑AuthenticationProviderManagerAuthenticationProvider

作者头像
JavaEdge
发布2018-12-14 17:08:38
3.3K0
发布2018-12-14 17:08:38
举报
文章被收录于专栏:JavaEdgeJavaEdge

Spring Security认证流程类图

核心验证器

AuthenticationManager

提供了认证方法的入口,接收一个Authentiaton对象作为参数

ProviderManager

AuthenticationManager的一个实现类

提供了基本的认证逻辑和方法 它包含了一个List<AuthenticationProvider>对象

通过 AuthenticationProvider接口来扩展出不同的认证提供者(当Spring Security默认提供的实现类不能满足需求的时候可以扩展AuthenticationProvider 覆盖supports(Class<?> authentication) 方法)

验证逻辑

  • AuthenticationManager接收 Authentication对象作为参数,并通过 authenticate(Authentication)方法对之验证
  • AuthenticationProvider实现类用来支撑对 Authentication对象的验证动作
  • UsernamePasswordAuthenticationToken实现了Authentication主要是将用户输入的用户名和密码进行封装,并供给 AuthenticationManager进行验证 验证完成以后将返回一个认证成功的 Authentication 对象

Authentication

Authentication接口中的主要方法

代码语言:javascript
复制
public interface Authentication extends Principal, Serializable {
    // 权限集合,可使用AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_ADMIN")返回字符串权限集合
    Collection<? extends GrantedAuthority> getAuthorities();
    // 用户名密码认证时可以理解为密码
    Object getCredentials();
    // 认证请求包含的一些附加信息(如 IP 地址,数字证书号)
    Object getDetails();
    // 用户名密码认证时可理解为用户名
    Object getPrincipal();
    // 是否被认证
    boolean isAuthenticated();
    // 设置是否能被认证
    void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException;

ProviderManager

AuthenticationManager的实现类,提供了基本认证实现逻辑和流程

代码语言:javascript
复制
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 1.获取当前的Authentication的认证类型
        Class<? extends Authentication> toTest = authentication.getClass();
        AuthenticationException lastException = null;
        Authentication result = null;
        boolean debug = logger.isDebugEnabled();
        
        // 2.遍历所有的 providers 使用 supports 方法判断该 provider 是否支持当前的认证类型
        for (AuthenticationProvider provider : getProviders()) {
            if (!provider.supports(toTest)) {
                continue;
            }

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

            try {
                // 3.若支持,调用 provider#authenticat 认证
                result = provider.authenticate(authentication);

                if (result != null) {
                    // 4.认证通过则重新生成 Authentication 对应的 Token
                    copyDetails(authentication, result);
                    break;
                }
            }
            catch (AccountStatusException e) {
                prepareException(e, authentication);
                // SEC-546: Avoid polling additional providers if auth failure is due to
                // invalid account status
                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 {
                // 5.如果 1 没有验证通过,则使用父类 AuthenticationManager 进行验证
                result = parent.authenticate(authentication);
            }
            catch (ProviderNotFoundException e) {
                // ignore as we will throw below if no other exception occurred prior to
                // calling parent and the parent
                // may throw ProviderNotFound even though a provider in the child already
                // handled the request
            }
            catch (AuthenticationException e) {
                lastException = e;
            }
        }
        // 6. 是否查出敏感信息
        if (result != null) {
            if (eraseCredentialsAfterAuthentication
                    && (result instanceof CredentialsContainer)) {
                // Authentication is complete. Remove credentials and other secret data
                // from authentication
                ((CredentialsContainer) result).eraseCredentials();
            }

            eventPublisher.publishAuthenticationSuccess(result);
            return result;
        }

        // Parent was null, or didn't authenticate (or throw an exception).

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

        prepareException(lastException, authentication);

        throw lastException;
    }
  • 遍历所有的 Providers,然后依次执行该 Provider 的验证方法
    • 如果某一个 Provider 验证成功,跳出循环不再执行后续的验证
    • 如果验证成功,会将返回的 result 即 Authentication 对象进一步封装为 Authentication Token,比如 UsernamePasswordAuthenticationToken、RememberMeAuthenticationToken 等 这些 Authentication Token 也都继承自 Authentication 对象
  • 如果 1 没有任何一个 Provider 验证成功,则试图使用其 parent Authentication Manager 进行验证
  • 是否需要擦除密码等敏感信息

AuthenticationProvider

AuthenticationProvider本身也就是一个接口 它的实现类AbstractUserDetailsAuthenticationProviderAbstractUserDetailsAuthenticationProvider的子类DaoAuthenticationProvider 是Spring Security中一个核心的Provider,对所有的数据库提供了基本方法和入口

DaoAuthenticationProvider

主要做了以下事情

对用户身份进行加密

1.可直接返回BCryptPasswordEncoder 也可自己实现该接口使用自己的加密算法

实现了 AbstractUserDetailsAuthenticationProvider 两个抽象方法

获取用户信息的扩展点
实现 additionalAuthenticationChecks 的验证方法(主要验证密码)

AbstractUserDetailsAuthenticationProvider

AbstractUserDetailsAuthenticationProvider为DaoAuthenticationProvider提供了基本的认证方法

代码语言:javascript
复制
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
                messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.onlySupports",
                        "Only UsernamePasswordAuthenticationToken is supported"));

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

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

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

            try {
                #1.获取用户信息由子类实现即DaoAuthenticationProvider
                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 {
            #2.前检查由DefaultPreAuthenticationChecks类实现(主要判断当前用户是否锁定,过期,冻结User接口)
            preAuthenticationChecks.check(user);
            #3.子类实现
            additionalAuthenticationChecks(user,
                    (UsernamePasswordAuthenticationToken) authentication);
        }
        catch (AuthenticationException exception) {
            if (cacheWasUsed) {
                // There was a problem, so try again after checking
                // we're using latest data (i.e. not from the cache)
                cacheWasUsed = false;
                user = retrieveUser(username,
                        (UsernamePasswordAuthenticationToken) authentication);
                preAuthenticationChecks.check(user);
                additionalAuthenticationChecks(user,
                        (UsernamePasswordAuthenticationToken) authentication);
            }
            else {
                throw exception;
            }
        }
        #4.检测用户密码是否过期对应#2 的User接口
        postAuthenticationChecks.check(user);

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

        Object principalToReturn = user;

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

        return createSuccessAuthentication(principalToReturn, authentication, user);
    }

AbstractUserDetailsAuthenticationProvider主要实现了AuthenticationProvider的接口方法 authenticate 并提供了相关的验证逻辑;

获取用户返回UserDetails AbstractUserDetailsAuthenticationProvider定义了一个抽象的方法

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.11.17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 核心验证器
    • AuthenticationManager
      • ProviderManager
      • 验证逻辑
      • Authentication
      • ProviderManager
      • AuthenticationProvider
        • DaoAuthenticationProvider
          • 对用户身份进行加密
          • 实现了 AbstractUserDetailsAuthenticationProvider 两个抽象方法
        • AbstractUserDetailsAuthenticationProvider
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档