串理spring security認證流程原始碼
1.認證流程流程
通過斷點除錯,可以看到在UsernamepasswordAuthenticationFilter中構造了一個
UsernamePasswordAuthenticationToken物件
開啟UsernamePasswordAuthenticationToken可得知,該實現類是Authentication的子類,因為Authentication是封裝了使用者的資訊。
在該建構函式中,其中super(null)是呼叫了父類的方法
,
父類的方法如下:
public AbstractAuthenticationToken(Collection<? extends GrantedAuthority> authorities) { if (authorities == null) { //為空時,需要賦個預設的許可權,因為此時還未進行身份認證 this.authorities = AuthorityUtils.NO_AUTHORITIES; return; } for (GrantedAuthority a : authorities) { if (a == null) { throw new IllegalArgumentException( "Authorities collection cannot contain any null elements"); } } ArrayList<GrantedAuthority> temp = new ArrayList<GrantedAuthority>( authorities.size()); temp.addAll(authorities); this.authorities = Collections.unmodifiableList(temp); }
setAuthenticated(false) 代表當前存進去的principal/credentials是否經過身份認證,此時肯定是沒有的。
setDetails(request, authRequest);
該方法會把請求的一些資訊設定到UsernamePasswordAuthenticationToken裡面去,包括當前發起請求的IP,Session等
return this.getAuthenticationManager().authenticate(authRequest); //往AuthenticationManager靠攏
AuthenticationManager該類本身不包含校驗的邏輯,它的作用是用來管理AuthenticationProvider
該方法會請求進入:ProviderManager.authenticate()方法,該類實現了AuthenticationManager介面
public Authentication authenticate(Authentication authentication) throws AuthenticationException { Class<? extends Authentication> toTest = authentication.getClass(); AuthenticationException lastException = null; Authentication result = null; boolean debug = logger.isDebugEnabled(); for (AuthenticationProvider provider : getProviders()) { // if (!provider.supports(toTest)) { continue; } /* getProviders() 拿到所有的AuthenticationProvider,校驗邏輯都是在Provider中 因為不同的登入方式,它的認證邏輯是不通 的,目前使用的使用者名稱+密碼的方式,後續還會有第三方登入,手機 號驗證碼登入等,provider.supports(toTest)是否支援當前的登入方式(判斷) 對於使用者名稱密碼方式,它傳遞的token是:UsernamePasswordAuthenticationToken,而對於第三方登入時的驗證方式則是SocialAuthenticationToken */ if (debug) { logger.debug("Authentication attempt using " + provider.getClass().getName()); } try { //具體執行校驗邏輯 result = provider.authenticate(authentication); if (result != null) { copyDetails(authentication, result); break; } } catch (AccountStatusException e) { prepareException(e, authentication); throw e; } catch (InternalAuthenticationServiceException e) { prepareException(e, authentication); throw e; } catch (AuthenticationException e) { lastException = e; } } if (result == null && parent != null) { // Allow the parent to try. try { result = parent.authenticate(authentication); } catch (ProviderNotFoundException e) { } catch (AuthenticationException e) { lastException = e; } } if (result != null) { if (eraseCredentialsAfterAuthentication && (result instanceof CredentialsContainer)) { ((CredentialsContainer) result).eraseCredentials(); } eventPublisher.publishAuthenticationSuccess(result); return result; } if (lastException == null) { lastException = new ProviderNotFoundException(messages.getMessage( "ProviderManager.providerNotFound", new Object[] { toTest.getName() }, "No AuthenticationProvider found for {0}")); } prepareException(lastException, authentication); throw lastException; }
provider.authenticate()實現類是寫在AuthenticationProvider的實現類AbstractUserDetailsAuthenticationProvider中
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.onlySupports",
"Only UsernamePasswordAuthenticationToken is supported"));
String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
: authentication.getName();
boolean cacheWasUsed = true;
UserDetails user = this.userCache.getUserFromCache(username);
if (user == null) {
cacheWasUsed = false;
try {
//獲取使用者資訊,具體實現類在:DaoAuthenticationProvider.retrieveUser()
user = retrieveUser(username,
(UsernamePasswordAuthenticationToken) authentication);
}
catch (UsernameNotFoundException notFound) {
logger.debug("User '" + username + "' not found");
if (hideUserNotFoundExceptions) {
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) {
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);
}
protected final UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
UserDetails loadedUser;
try {
loadedUser = this.getUserDetailsService().loadUserByUsername(username);
/**
getUserDetailService在呼叫我們提供的UserDetailService的實現,也就是:MyUserDetailsService
*/
}
catch (UsernameNotFoundException notFound) {
if (authentication.getCredentials() != null) {
String presentedPassword = authentication.getCredentials().toString();
passwordEncoder.isPasswordValid(userNotFoundEncodedPassword,
presentedPassword, null);
}
throw notFound;
}
catch (Exception repositoryProblem) {
throw new InternalAuthenticationServiceException(
repositoryProblem.getMessage(), repositoryProblem);
}
if (loadedUser == null) {
throw new InternalAuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation");
}
return loadedUser;
}
拿到使用者資訊之後,回到AbstractUserDetailsAuthenticationProvider
try {
preAuthenticationChecks.check(user);
additionalAuthenticationChecks(user,
(UsernamePasswordAuthenticationToken) authentication);
//在dao裡校驗密碼是否匹配
}
它會預檢查使用者是否過期,是否禁用,之後檢查密碼是否匹配。
預檢查之後還會有後置檢查
postAuthenticationChecks.check(user); //
所有檢查都通過,就會認為使用者的認證是成功的。
return createSuccessAuthentication(principalToReturn, authentication, user);
protected Authentication createSuccessAuthentication(Object principal,
Authentication authentication, UserDetails user) {
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
principal, authentication.getCredentials(),
authoritiesMapper.mapAuthorities(user.getAuthorities()));
result.setDetails(authentication.getDetails());
return result;
}
再次new 了UsernamePasswordAuthenticationToken物件,區別再與構造方法不同,傳遞的引數不同,這個時候許可權,使用者資訊都已經拿到
2.認證結果如何在多個請求之間共享
3.獲取使用者認證的資訊