Spring security(三)---认证过程

  在前面两节Spring security (一)架构框架-Component、Service、Filter分析Spring Security(二)--WebSecurityConfigurer配置以及filter顺序为Spring Security认证作好了准备,可以让我们更好的理解认证过程以及项目代码编写。

1.认证过程工作流程

认证工作流程:

    AbstractAuthenticationProcessingFilter
    doFilter()(attemptAuthentication()获取Authentication实体)
        ->UsernamePasswordAuthenticationFilter(AbstractAuthenticationProcessingFilter的子类)
            attemptAuthentication() (在UsernamePasswordAuthenticationToken()中将username 和 password 生成 UsernamePasswordAuthenticationToken对象,getAuthenticationManager().authenticate进行认证以及返回获取Authentication实体)
                ->AuthenticationManager
             ->ProviderManager()(AuthenticationManager接口实现)
                     authenticate()(AuthenticationProvider.authenticate()进行认证并获取Authentication实体)
                        ->AbstractUserDetailsAuthenticationProvider(内置缓存机制,如果缓存中没有用户信息就调用retrieveUser()获取用户)
                authenticate()  (获取Authentication实体需要userDetails,在缓存中或者retrieveUser()获取userDetails;验证additionalAuthenticationChecks();     createSuccessAuthentication()生成Authentication实体)
                ->DaoAuthenticationProvider
                    retrieveUser()  (调用自定义UserDetailsService中loadUserByUsername()加载userDetails)
                    ->UserDetailsService   
                        loadUserByUsername()(获取userDetails)

具体流程请看下面小节。

1.1:请求首先经过过滤器AbstractAuthenticationProcessingFilter以及UsernamePasswordAuthenticationFilter进行处理

  当请求来临时,在默认情况下,请求先经过AbstractAuthenticationProcessingFilter的子类UsernamePasswordAuthenticationFilter过滤器。在UsernamePasswordAuthenticationFilter过滤器调用attemptAuthentication()方法现实主要的两步过程:

  1. 创建拥有用户的详情信息的Authentication对象,在默认的UsernamePasswordAuthenticationFilter中将创建UsernamePasswordAuthenticationToken的Authentication对象;
  2. AuthenticationManager调用authenticate()方法进行认证过程,在默认情况,使用ProviderManager类进行认证。

UsernamePasswordAuthenticationFilter源码分析:

    public class UsernamePasswordAuthenticationFilter extends
        AbstractAuthenticationProcessingFilter {
        ....
        public Authentication attemptAuthentication(HttpServletRequest request,
            HttpServletResponse response) throws AuthenticationException {
            .....
            //1.创建拥有用户的详情信息的Authentication对象
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);
                //2.AuthenticationManager进行认证
        return this.getAuthenticationManager().authenticate(authRequest);
    }
    ...
   }  

1.2请求经过过滤器处理之后,在AuthenticationManager以及ProviderManager认证

  在UsernamePasswordAuthenticationFilter中看出,将调用AuthenticationManager接口的authenticate()方法进行详细认证。默认情况将使用AuthenticationManager子类ProviderManager的authenticate()进行认证,可以分成三个主要过程:

  1. AuthenticationProvide.authenticate()进行认证,默认下,将使用AbstractUserDetailsAuthenticationProvider进行认证;
  2. 认证成功后,从authentication中删除凭据和其他机密数据,否则抛出异常或者认证失败;
  3. 发布认证成功事件,并将Authentication对象保存到security context中。

ProviderManager源码分析:

public class ProviderManager implements AuthenticationManager, MessageSourceAware,
    InitializingBean {
    ...
        public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
                ...
                //AuthenticationProvider依次进行认证
        for (AuthenticationProvider provider : getProviders()) {
                ...
            try {
                    //1.1进行认证,并返回Authentication对象
                result = provider.authenticate(authentication);

                if (result != null) {
                    copyDetails(authentication, result);
                    break;
                }
            }
                ...
            catch (AuthenticationException e) {
                lastException = e;
            }
        }
        if (result == null && parent != null) {
            // Allow the parent to try.
            try {
                    //1.2如果1.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;
            }
        }
                //2.从authentication中删除凭据和其他机密数据
        if (result != null) {
            if (eraseCredentialsAfterAuthentication
                    && (result instanceof CredentialsContainer)) {
                // Authentication is complete. Remove credentials and other secret data
                // from authentication
                ((CredentialsContainer) result).eraseCredentials();
            }
              //3.发布认证成功事件,并将Authentication对象保存到security context中
            eventPublisher.publishAuthenticationSuccess(result);
            return result;
        }
    }

1.3 认证过程详细处理:AuthenticationProvider、AbstractUserDetailsAuthenticationProvider以及DaoAuthenticationProvider

  在默认认证详细处理过程中,AuthenticationProvider认证由AbstractUserDetailsAuthenticationProvider抽象类以及AbstractUserDetailsAuthenticationProvider的子类DaoAuthenticationProvider进行方法重写协助共同工作进行认证的。主要可以分成以下步骤:

  1. 获取用户信息UserDetails,首先从缓存中读取信息,如果缓存中没有的化,在UserDetailsService中加载,其最主要可以从我们自定义的UserDetailsService进行读取用户信息UserDetails;

  2. 验证三步走:
    1). preAuthenticationChecks

    2). additionalAuthenticationChecks:使用PasswordEncoder.matches()方法进行认证,其验证方式中验证数据已经过PasswordEncoder算法加密,可以通过实现PasswordEncoder接口来定义算法加密方式。

    3). postAuthenticationChecks

  3. 将已通过验证的用户信息封装成 UsernamePasswordAuthenticationToken对象并返回;该对象封装了用户的身份信息,以及相应的权限信息。

  AbstractUserDetailsAuthenticationProvider主要功能提供authenticate()认证方法以及给DaoAuthenticationProvider重写方法源码分析:

    public abstract class AbstractUserDetailsAuthenticationProvider implements
        AuthenticationProvider, InitializingBean, MessageSourceAware {
        ...
        public Authentication authenticate(Authentication authentication)
        throws AuthenticationException {
                   ...
            boolean cacheWasUsed = true;
            //1.1获取缓存中UserDetails信息
            UserDetails user = this.userCache.getUserFromCache(username);
                  //1.2 如果缓存中没有信息,从UserDetailsService中获取
            if (user == null) {
                cacheWasUsed = false;
    
                try {
                        //使用DaoAuthenticationProvider中重写的方法去获取信息
                    user = retrieveUser(username,
                            (UsernamePasswordAuthenticationToken) authentication);
                }catch{
                ...
                }
                ...
            try {
                    //进行检验认证
                preAuthenticationChecks.check(user);
                additionalAuthenticationChecks(user,
                        (UsernamePasswordAuthenticationToken) authentication);
            }catch{
            ...
            }
                ...
            postAuthenticationChecks.check(user);
                   ....
                   // 将已通过验证的用户信息封装成 UsernamePasswordAuthenticationToken对象并返回
            return createSuccessAuthentication(principalToReturn, authentication, user);
    }

  DaoAuthenticationProvider功能主要为认证凭证加密PasswordEncoder,以及重写AbstractUserDetailsAuthenticationProvider抽象类的retrieveUser、additionalAuthenticationChecks方法,其中retrieveUser主要是获取UserDetails信息,源码分析

    protected final UserDetails retrieveUser(String username,
        UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    prepareTimingAttackProtection();
    try {
            //根据UserDetailsService获取UserDetails信息,从自定义的UserDetailsService获取
        UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);
        if (loadedUser == null) {
            throw new InternalAuthenticationServiceException(
                    "UserDetailsService returned null, which is an interface contract violation");
        }
        return loadedUser;
    }
    catch (UsernameNotFoundException ex) {
        mitigateAgainstTimingAttack(authentication);
        throw ex;
    }
    catch (InternalAuthenticationServiceException ex) {
        throw ex;
    }
    catch (Exception ex) {
        throw new InternalAuthenticationServiceException(ex.getMessage(), ex);
    }
}

additionalAuthenticationChecks主要使用PasswordEncoder进行密码验证,源码分析:

protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    if (authentication.getCredentials() == null) {
        logger.debug("Authentication failed: no credentials provided");

        throw new BadCredentialsException(messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.badCredentials",
                "Bad credentials"));
    }

    String presentedPassword = authentication.getCredentials().toString();
        //进行密码验证
    if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
        logger.debug("Authentication failed: password does not match stored value");

        throw new BadCredentialsException(messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.badCredentials",
                "Bad credentials"));
    }
}

1.4 认证中所需的认证凭证获取:UserDetailsService

  在认证中必须获取认证凭证,从UserDetailsService获取到认证凭证,UserDetailsService接口只有一个方法:

UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;

通过用户名 username 调用方法 loadUserByUsername 返回了一个UserDetails接口对象:

public interface UserDetails extends Serializable {
    //1.权限集合
    Collection<? extends GrantedAuthority> getAuthorities();
    //2.密码  
    String getPassword();
    //3.用户名
    String getUsername();
    //4.用户是否过期
    boolean isAccountNonExpired();
    //5.是否锁定    
    boolean isAccountNonLocked();
    //6.用户密码是否过期    
    boolean isCredentialsNonExpired();
    //7.账号是否可用(可理解为是否删除)
    boolean isEnabled();
}

我们通过实现UserDetailsService自定义获取UserDetails类,可以从不同数据源中获取认证凭证。

1.5 总结

总结Spring Security(二)--WebSecurityConfigurer配置以及filter顺序和本节Spring security(三)想要实现简单认证过程:

  1. 第一步:配置WebSecurityConfig
  2. 第二步: 实现自定义UserDetailsService,自定义从数据源码获取认证凭证。

2 Spring boot与Spring security整合

2.1配置WebSecurityConfig

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        //super.configure(http);
        http .csrf().disable()
             .authorizeRequests()
             .anyRequest().authenticated()
              .and()
             .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login/form")
                .failureUrl("/login-error")
                .permitAll()  //表单登录,permitAll()表示这个不需要验证 登录页面,登录失败页面
              .and()
                .logout().permitAll();
        }
}

2.2 UserDetailsService实现

@service
public class CustomUserService implements UserDetailsService {
 @Autowired
 private UserInfoMapper userInfoMapper;
 @Autowired
 private PermissionInfoMapper permissionInfoMapper;
 @Autowired
 private BCryptPasswordEncoderService bCryptPasswordEncoderService;
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        //这里可以可以通过username(登录时输入的用户名)然后到数据库中找到对应的用户信息,并构建成我们自己的UserInfo来返回。
        UserInfoDTO user = userInfoMapper.getUserInfoByUserName(username);
         if (user != null) {
        List<PermissionInfoDTO> permissionInfoDTOS = permissionInfoMapper.findByAdminUserId(userInfo.getId());
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        for (PermissionInfoDTO permissionInfoDTO : permissionInfoDTOS) {
            if (permissionInfoDTO != null && permissionInfoDTO.getPermissionName() != null) {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(
                        permissionInfoDTO.getPermissionName());
                grantedAuthorityList.add(grantedAuthority);
                 }
            }
             return new User(userInfo.getUserName(), bCryptPasswordEncoderService.encode(userInfo.getPasswaord()), grantedAuthorityList);
         }else {
        throw new UsernameNotFoundException("admin" + username + "do not exist");
         }
    }
}

2.3 github代码

链接

  后续会spring security认证的扩展知识Spring Security OAuth2等,以及项目demo:Spring Security OAuth2 整合 JWT、ip、短信以及微信方式登陆的代码分析与分享。最后如有错误可评论告知。

最后可关注公众号,一起学习。加群,每天会分享干货,还有学习视频领取!

image
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,657评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,889评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,057评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,509评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,562评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,443评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,251评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,129评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,561评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,779评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,902评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,621评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,220评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,838评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,971评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,025评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,843评论 2 354

推荐阅读更多精彩内容