在前面两节Spring security (一)架构框架-Component、Service、Filter分析和Spring Security(二)--WebSecurityConfigurer配置以及filter顺序为Spring Security认证做好了准备,可让咱们更好的理解认证过程以及项目代码编写。html
认证工做流程: 算法
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)
具体流程请看下面小节。数据库
当请求来临时,在默认状况下,请求先通过AbstractAuthenticationProcessingFilter的子类UsernamePasswordAuthenticationFilter过滤器。在UsernamePasswordAuthenticationFilter过滤器调用attemptAuthentication()方法现实主要的两步过程:缓存
建立拥有用户的详情信息的Authentication对象,在默认的UsernamePasswordAuthenticationFilter中将建立UsernamePasswordAuthenticationToken的Authentication对象;架构
AuthenticationManager调用authenticate()方法进行认证过程,在默认状况,使用ProviderManager类进行认证。 app
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); } ... }
在UsernamePasswordAuthenticationFilter中看出,将调用AuthenticationManager接口的authenticate()方法进行详细认证。默认状况将使用AuthenticationManager子类ProviderManager的authenticate()进行认证,能够分红三个主要过程:ide
AuthenticationProvide.authenticate()进行认证,默认下,将使用AbstractUserDetailsAuthenticationProvider进行认证;源码分析
认证成功后,从authentication中删除凭据和其余机密数据,不然抛出异常或者认证失败;post
发布认证成功事件,并将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; } }
在默认认证详细处理过程当中,AuthenticationProvider认证由AbstractUserDetailsAuthenticationProvider抽象类以及AbstractUserDetailsAuthenticationProvider的子类DaoAuthenticationProvider进行方法重写协助共同工做进行认证的。主要能够分红如下步骤:
获取用户信息UserDetails,首先从缓存中读取信息,若是缓存中没有的化,在UserDetailsService中加载,其最主要能够从咱们自定义的UserDetailsService进行读取用户信息UserDetails;
验证三步走: 1). preAuthenticationChecks
2). additionalAuthenticationChecks:使用PasswordEncoder.matches()方法进行认证,其验证方式中验证数据已通过PasswordEncoder算法加密,能够经过实现PasswordEncoder接口来定义算法加密方式。
3). postAuthenticationChecks
将已经过验证的用户信息封装成 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")); } }
在认证中必须获取认证凭证,从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类,能够从不一样数据源中获取认证凭证。
总结Spring Security(二)--WebSecurityConfigurer配置以及filter顺序和本节Spring security(三)想要实现简单认证过程:
第一步:配置WebSecurityConfig
第二步: 实现自定义UserDetailsService,自定义从数据源码获取认证凭证。
@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(); } }
@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"); } } }
往期文章:
...
各位看官还能够吗?喜欢的话,动动手指点个赞💗,点个关注呗!!谢谢支持!
也欢迎关注公众号【Ccww笔记】,原创技术文章第一时间推出
getAuthenticationManager().authenticate进行认证以及返回获取Authentication实体)
原文出处:https://www.cnblogs.com/Ccwwlx/p/12033546.html