写点什么

Spring Security 密码登录流程源码分析

用户头像
读钓
关注
发布于: 2020 年 05 月 24 日
Spring Security密码登录流程源码分析

初识

Spring Security是通过SecuriyFilterChains过滤器链来保证应用安全的,而这些过滤器链由FilterChainProxy(本质上是个Filter)来管理,每个uri都对应一个SecurityFilterChain,即对应SecurityFilterChain中的Filters。



FilterChainProxy中由SecurityFilterChain维护了很多Filter,debug进入可以看到:

SpringSecurity的密码登录就是由UsernamePasswordAuthenticationFilter过滤器来实现的,先上一张登录校验流程图:



UsernamePasswordAuthenticationFilter

UsernamePasswordAuthenticationFilter 继承了 AbstractAuthenticationProcessingFilter,doFilter()方法由其父类实现。

doFilter()方法中调用了attemptAuthentication()方法,该方法尝试进行身份验证,由UsernamePasswordAuthenticationFilter实现,关键代码如下:

public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
// 判断请求方式
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
// 获取用户名密码
String username = obtainUsername(request);
String password = obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
// 使用用户名密码生成token
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
username, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
// 根据token,匹配合适的provider认证
return this.getAuthenticationManager().authenticate(authRequest);
}

ProviderManager

ProviderManager#authenticate() 会获取所有的AuthenticationProvider,然后遍历,找出与封装的 Token 匹配的 Provider,调用其 authenticate()方法。

public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
Class<? extends Authentication> toTest = authentication.getClass();
AuthenticationException lastException = null;
AuthenticationException parentException = null;
Authentication result = null;
Authentication parentResult = null;
boolean debug = logger.isDebugEnabled();
for (AuthenticationProvider provider : getProviders()) {
// 遍历所有Providers,找到与token相匹配的provider
if (!provider.supports(toTest)) {
continue;
}
if (debug) {
logger.debug("Authentication attempt using "
+ provider.getClass().getName());
}
try {
// 调用authenticate方法认证,拿到认证结果
result = provider.authenticate(authentication);
if (result != null) {
copyDetails(authentication, result);
break;
}
}
catch (AccountStatusException | InternalAuthenticationServiceException e) {
prepareException(e, authentication);
// SEC-546: Avoid polling additional providers if auth failure is due to
// invalid account status
throw e;
} catch (AuthenticationException e) {
lastException = e;
}
}
if (result == null && parent != null) {
// Allow the parent to try.
try {
result = parentResult = 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 = parentException = e;
}
}
if (result != null) {
if (eraseCredentialsAfterAuthentication
&& (result instanceof CredentialsContainer)) {
// 认证完成,移除密码等敏感信息
// Authentication is complete. Remove credentials and other secret data
// from authentication
((CredentialsContainer) result).eraseCredentials();
}
// If the parent AuthenticationManager was attempted and successful than it will publish an AuthenticationSuccessEvent
// This check prevents a duplicate AuthenticationSuccessEvent if the parent AuthenticationManager already published it
if (parentResult == null) {
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}"));
}
// If the parent AuthenticationManager was attempted and failed than it will publish an AbstractAuthenticationFailureEvent
// This check prevents a duplicate AbstractAuthenticationFailureEvent if the parent AuthenticationManager already published it
if (parentException == null) {
prepareException(lastException, authentication);
}
throw lastException;
}

provider.supports方法,以token(authentication)的类型为标准,判断是否是UsernamePasswordAuthenticationToken类或其子类,为扩展UsernamePasswordAuthenticationToken提供了基础。

public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class
.isAssignableFrom(authentication));
}

认证完成后,还会调用eraseCredentials()方法,进行密码擦除工作,比如把密码置空。



AbstractUserDetailsAuthenticationProvider

ProviderManager#authenticate() 方法,进入AbstractUserDetailsAuthenticationProviderauthenticate 方法。

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();
// 先从缓存中获取UserDetails
boolean cacheWasUsed = true;
UserDetails user = this.userCache.getUserFromCache(username);
if (user == null) {
cacheWasUsed = false;
try {
// 获取UserDetails
user = retrieveUser(username,
(UsernamePasswordAuthenticationToken) authentication);
}
catch (UsernameNotFoundException notFound) {
logger.debug("User '" + username + "' not found");
if (hideUserNotFoundExceptions) {
// 隐藏用户不存在异常,统一抛出BadCredentialsException
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 {
// 用户状态前置校验:账户锁定、不可用、过期
preAuthenticationChecks.check(user);
// 这里主要是校验密码是否正确
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;
}
}
// 用户状态后置校验:账户密码过期
postAuthenticationChecks.check(user);
if (!cacheWasUsed) {
this.userCache.putUserInCache(user);
}
Object principalToReturn = user;
if (forcePrincipalAsString) {
principalToReturn = user.getUsername();
}
return createSuccessAuthentication(principalToReturn, authentication, user);
}

重点关注获取用户信息retrieveUser()和密码校验additionalAuthenticationChecks()方法,他们都是抽象方法,由其子类 DaoAuthenticationProvider 实现。

DaoAuthenticationProvider

retrieveUser()

protected final UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
prepareTimingAttackProtection();
try {
// 根据username获取UserDetails
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);
}
}

最终调用了 UserDetailsService 的 loadUserByUsername()方法,来获取用户信息,我们可以实现 UserDetailsService 接口,从数据库中查出用户的信息。

additionalAuthenticationChecks()

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"));
}
}

使用了passwordEncoder.matches()方法来匹配密码是否相同。

总结

最后再看下这张流程图,就比较清晰了

梳理一下整个认证流程:

通过过滤器获取请求参数,封装成token,调用 ProviderManager 管理的 Provider (认证逻辑的实现类) 的 authenticate 方法,最后调用 UserDetailService 去获取用户的信息,之后做一下前置、后置和密码的校验。



可以留言说下你学习源码的感受,你的评论、在看、转发,都能让我高兴好久。

发布于: 2020 年 05 月 24 日阅读数: 73
用户头像

读钓

关注

Java开发,专心练剑 2017.11.10 加入

公众号:读钓的YY,欢迎关注

评论

发布
暂无评论
Spring Security密码登录流程源码分析