很多小伙伴 对于SpringSecurity框架 只是知道 用的来,但是面试的时候,叫他或者她说一下 认证或者授权的原理或者流程是怎样的,突然,大部分人一下就开不了口,这样就导致面试的时候,被削减工资 。今天就给大家说说 SpringSecurity的认证原理。
看一下认证流程的流程图 :

其实 你把这个流程图看懂,基本认证的源码你就知道了。
下面就来分析一下认证的原理 :
小伙伴 还记到 我在类上 配置的 @EnableWebSecurity这个注解吧,点击进去看 有个@EnableGlobalAuthenticaiton这个注解就和认证有关系了。

在进入@EnableGlobalAuthenticaiton 这个注解 看到一个类 AuthenticationConfiguration这个类,这个类就关键了

进入该类 找到 authentication方法(关键方法)
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (this.delegate != null) {
return this.delegate.authenticate(authentication);
} else {
Object var2 = this.delegateMonitor;
synchronized(this.delegateMonitor) {
if (this.delegate == null) {
this.delegate = (AuthenticationManager)this.delegateBuilder.getObject();
this.delegateBuilder = null;
}
}
return this.delegate.authenticate(authentication);
}
}
在进行 点进去 AuthenticationManager 这里面
public interface AuthenticationManager {
Authentication authenticate(Authentication var1) throws AuthenticationException;
}
小伙伴 请看 这个是不是 上面图的 ,他是一个接口,找到对应的实现类ProviderManager类,这个类维护了一个集合
private List providers; 这个集合就提供很多的认证方式,比如用户名 密码认证 短信认证 等
我们还是看关键的 该了的 authenticate方法,这个是认证方法 ,找到方法里面的
result = provider.authenticate(authentication);代码,在点击进去
最终会点进入 AbstractUserDetailsAuthenticationProvider 类的 authenticate方法,
这个方法的关键代码
user = this.retrieveUser(username, (UsernamePasswordAuthenticationToken)authentication);
进入retrieveUser 方法 就会明白原理了
protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
this.prepareTimingAttackProtection();
try {
//这个方法是不是很熟悉。
UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);
if (loadedUser == null) {
throw new InternalAuthenticationServiceException(“UserDetailsService returned null, which is an interface contract violation”);
} else {
return loadedUser;
}
} catch (UsernameNotFoundException var4) {
this.mitigateAgainstTimingAttack(authentication);
throw var4;
} catch (InternalAuthenticationServiceException var5) {
throw var5;
} catch (Exception var6) {
throw new InternalAuthenticationServiceException(var6.getMessage(), var6);
}
}
到这里 下面的我不用讲了吧,认证就这样的流程,一切都在图中 和 代码中…
注意:如果转载 请标明出处 谢谢… 创作不容易。。。
1682



被折叠的 条评论
为什么被折叠?



