Spring security 浅谈用户验证机制

step1:首先ApplicationUserDetailsService需要实现UserDetailsService接口(在

org.springframework.security.core.userdetails里面),实现获取用户Details信息的回调函数,必须要实现

loadUserByUsername方法,注意这里的User实现了UserDetails,CredentialsContainer,User类里面的参数分别有:

password,username,authorities,accountNonExpired,accountNonLocked,credentialsNonExpired,enable,

代码如下:

 

我们可以自定义添加新的User信息,这里我们自定义一个SimpleUser类继承User。

代码如下:

 

注意这里的SimpleUser必须继承User,而且必须继承上面这5个属性和hashCode,equals方法,构造方法中必须给上述这5个

属性赋值,ApplicationUserDetailsService调用构造方法,生成一个SimpleUser对象。如果user不存在,抛出一个

UsernameNotFoundException异常。

代码如下:

 

step2:loadUserByUsername方法返回后,会跳到DaoAuthenticationProvider(在

org.springframework.security.authentication.dao)类中的retrieveUser方法中

 

step3:retrieveUser方法返回后,会跳到AbstractUserDetailsAuthenticationProvider(在

org.springframework.security.authentication.dao)authenticate方法中,这个方法会先从缓存中查找user。

 

如果没有的话会从上一步DaoAuthenticationProvider的loadUserByUsername方法中把user查出来,这里会抛出

UserNameNotFoundException这个异常,应该是用户不存在这个错误,即Bad credentials。

step4:authenticate方法preAuthenticationChecks.check(user),这里进行基本有效性验证(是否有效,是否

被锁,是否过期)代码如下:

 

step5:authenticate方法中additionalAuthenticationChecks(user,

(UsernamePasswordAuthenticationToken) authentication)这里进行方法验证。代码如下:

 

原文地址:https://www.cnblogs.com/hengzhou/p/9353013.html