shiro 認(rèn)證流程操作
一、背景
我們可以使用 shiro 進(jìn)行認(rèn)證操作,下面粘貼的是 LoginController 的代碼,模擬用戶登錄的請求操作:
@Controller @Slf4j public class LoginController { @RequestMapping("/login") public String login(User user) { if (StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())) { return "error"; } //用戶認(rèn)證信息 Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken( user.getUserName(), user.getPassword()); usernamePasswordToken.setRememberMe(true); try { //進(jìn)行驗(yàn)證,這里可以捕獲異常,然后返回對應(yīng)信息 subject.login(usernamePasswordToken); } catch (UnknownAccountException e) { log.error("用戶名不存在!", e); return "error"; } catch (AuthenticationException e) { log.error("賬號或密碼錯誤!", e); return "error"; } catch (AuthorizationException e) { log.error("沒有權(quán)限!", e); return "error"; } return "shiro_index"; } }
二、源碼追蹤分析
我們先獲取用戶輸入的 userName 和 passWord ,然后將 userName 和 passWord 這兩個參數(shù)傳入到 UsernamePasswordToken 中獲取 token 對象,最后調(diào)用SecurityUtils.getSubject() 的 login() 方法將 token 傳入做系統(tǒng)校驗(yàn)。
我們進(jìn)入源碼查看下 login() 方法底層是如何實(shí)現(xiàn)的,可以看到主要還是調(diào)用了 securityManager 安全管理器的 login() 方法。
public void login(AuthenticationToken token) throws AuthenticationException { clearRunAsIdentitiesInternal(); // 主要是這塊的方法 Subject subject = securityManager.login(this, token); PrincipalCollection principals; String host = null; if (subject instanceof DelegatingSubject) { DelegatingSubject delegating = (DelegatingSubject) subject; //we have to do this in case there are assumed identities - we don't want to lose the 'real' principals: principals = delegating.principals; host = delegating.host; } else { principals = subject.getPrincipals(); } if (principals == null || principals.isEmpty()) { String msg = "Principals returned from securityManager.login( token ) returned a null or " + "empty value. This value must be non null and populated with one or more elements."; throw new IllegalStateException(msg); } this.principals = principals; this.authenticated = true; if (token instanceof HostAuthenticationToken) { host = ((HostAuthenticationToken) token).getHost(); } if (host != null) { this.host = host; } Session session = subject.getSession(false); if (session != null) { this.session = decorate(session); } else { this.session = null; } }
我們繼續(xù)進(jìn)入源碼查看 securityManager 安全管理器的 login() 方法是如何實(shí)現(xiàn)的,可以看到在這個方法中定義了 AuthenticationInfo 對象來接收從 Relam 傳來的認(rèn)證信息。
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException { AuthenticationInfo info; try { // 主要是這塊的方法 info = authenticate(token); } catch (AuthenticationException ae) { try { onFailedLogin(token, ae, subject); } catch (Exception e) { if (log.isInfoEnabled()) { log.info("onFailedLogin method threw an " + "exception. Logging and propagating original AuthenticationException.", e); } } throw ae; //propagate } Subject loggedIn = createSubject(token, info, subject); onSuccessfulLogin(token, info, loggedIn); return loggedIn; }
我們繼續(xù)進(jìn)入源碼查看 authenticate() 方法是如何實(shí)現(xiàn)的,我們發(fā)現(xiàn)這個方法內(nèi)部調(diào)用了 authenticator 對象的 authenticate() 方法。
public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException { return this.authenticator.authenticate(token); }
我們繼續(xù)進(jìn)入源碼查看 authenticator 對象的 authenticate() 方法是如何實(shí)現(xiàn)的。我們發(fā)現(xiàn)在這個方法的內(nèi)部調(diào)用了 doAuthenticate() 方法。
public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException { if (token == null) { throw new IllegalArgumentException("Method argument (authentication token) cannot be null."); } log.trace("Authentication attempt received for token [{}]", token); AuthenticationInfo info; try { // 主要看這塊的代碼 info = doAuthenticate(token); if (info == null) { String msg = "No account information found for authentication token [" + token + "] by this " + "Authenticator instance. Please check that it is configured correctly."; throw new AuthenticationException(msg); } } catch (Throwable t) { AuthenticationException ae = null; if (t instanceof AuthenticationException) { ae = (AuthenticationException) t; } if (ae == null) { //Exception thrown was not an expected AuthenticationException. Therefore it is probably a little more //severe or unexpected. So, wrap in an AuthenticationException, log to warn, and propagate: String msg = "Authentication failed for token submission [" + token + "]. Possible unexpected " + "error? (Typical or expected login exceptions should extend from AuthenticationException)."; ae = new AuthenticationException(msg, t); if (log.isWarnEnabled()) log.warn(msg, t); } try { notifyFailure(token, ae); } catch (Throwable t2) { if (log.isWarnEnabled()) { String msg = "Unable to send notification for failed authentication attempt - listener error?. " + "Please check your AuthenticationListener implementation(s). Logging sending exception " + "and propagating original AuthenticationException instead..."; log.warn(msg, t2); } } throw ae; } log.debug("Authentication successful for token [{}]. Returned account [{}]", token, info); notifySuccess(token, info); return info; }
我們繼續(xù)進(jìn)入源碼查看 doAuthenticate() 方法是如何實(shí)現(xiàn)的。我們發(fā)現(xiàn)在這個方法的內(nèi)部調(diào)用了 doAuthenticate() 方法。
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException { assertRealmsConfigured(); Collection<Realm> realms = getRealms(); if (realms.size() == 1) { return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken); } else { return doMultiRealmAuthentication(realms, authenticationToken); } }
這個 assertRealmsConfigured() 方法是判斷 relam 是否存在,若不存在就會拋出異常,它會根據(jù) relam 的個數(shù)來判斷執(zhí)行哪個方法,我在上一篇文章中只定義了一個 relam ,所以它會執(zhí)行 doSingleRealmAuthentication() 這個方法,并且會將 relam 和 token 傳入進(jìn)去。
我們繼續(xù)進(jìn)入源碼查看 doSingleRealmAuthentication() 方法是如何實(shí)現(xiàn)的, 我們可以看到,在這里它會先判斷 realm 是否支持 token ,若支持,則接下來執(zhí)行 getAuthenticationInfo() 方法。
protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) { if (!realm.supports(token)) { String msg = "Realm [" + realm + "] does not support authentication token [" + token + "]. Please ensure that the appropriate Realm implementation is " + "configured correctly or that the realm accepts AuthenticationTokens of this type."; throw new UnsupportedTokenException(msg); } AuthenticationInfo info = realm.getAuthenticationInfo(token); if (info == null) { String msg = "Realm [" + realm + "] was unable to find account data for the " + "submitted AuthenticationToken [" + token + "]."; throw new UnknownAccountException(msg); } return info; }
我們繼續(xù)進(jìn)入源碼查看 getAuthenticationInfo() 方法是如何實(shí)現(xiàn)的, getCachedAuthenticationInfo() 方法是從 shiro 緩存中讀取用戶信息,如果沒有,才會從 relam 中獲取,如果是第一次登錄,緩存中指定沒有我們的認(rèn)證信息,所以會執(zhí)行 doGetAuthenticationInfo() 這個方法。
public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { AuthenticationInfo info = getCachedAuthenticationInfo(token); if (info == null) { //otherwise not cached, perform the lookup: info = doGetAuthenticationInfo(token); log.debug("Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info); if (token != null && info != null) { cacheAuthenticationInfoIfPossible(token, info); } } else { log.debug("Using cached authentication info [{}] to perform credentials matching.", info); } if (info != null) { assertCredentialsMatch(token, info); } else { log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token); } return info; }
我們繼續(xù)進(jìn)入源碼查看 doGetAuthenticationInfo() 方法是如何實(shí)現(xiàn)的,我們發(fā)現(xiàn)其實(shí)現(xiàn)類有如下幾個,其中 CustomRealm 就是我們自定義實(shí)現(xiàn)的。
我們再來看一下,我們自定義的 CustomRealm 中的 doGetAuthenticationInfo() 代碼 ,這個方法就是需要查詢數(shù)據(jù)庫中的數(shù)據(jù)并進(jìn)行一個簡單的校驗(yàn),最后封裝成 SimpleAuthorizationInfo 對象再返回去。
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { if(StringUtils.isEmpty(authenticationToken.getPrincipal())) { return null; } // 獲取用戶信息 String userName = authenticationToken.getPrincipal().toString(); User user = userService.selectByUserName(userName); // 用戶是否存在 if(user == null) { throw new UnknownAccountException(); } // 是否激活 if(user !=null && user.getStatus().equals("0")){ throw new DisabledAccountException(); } // 是否鎖定 if(user!=null && user.getStatus().equals("3")){ throw new LockedAccountException(); } // 若存在將此用戶存放到登錄認(rèn)證info中,無需做密碼比對shiro會為我們進(jìn)行密碼比對校驗(yàn) if(user !=null && user.getStatus().equals("1")){ ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUserName()+ "salt"); /** 這里驗(yàn)證authenticationToken和simpleAuthenticationInfo的信息,構(gòu)造方法支持三個或者四個參數(shù), * 第一個參數(shù)傳入userName或者是user對象都可以。 * 第二個參數(shù)傳入數(shù)據(jù)庫中該用戶的密碼(記得是加密后的密碼) * 第三個參數(shù)傳入加密的鹽值,若沒有則可以不加 * 第四個參數(shù)傳入當(dāng)前Relam的名字 **/ SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, user.getPassword().toString(),credentialsSalt, getName()); return simpleAuthenticationInfo; } return null; }
截至到目前為止,我們算是獲取到了認(rèn)證信息了,接下來就是看下 shiro 是怎么進(jìn)行認(rèn)證的,我們返回去再看下 AuthenticatingRealm 類的 getAuthenticationInfo() 方法,我們可以看到,獲取完信息之后就需要進(jìn)行密碼匹配,會調(diào)用 assertCredentialsMatch() 方法。
public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { AuthenticationInfo info = getCachedAuthenticationInfo(token); if (info == null) { //otherwise not cached, perform the lookup: info = doGetAuthenticationInfo(token); log.debug("Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info); if (token != null && info != null) { cacheAuthenticationInfoIfPossible(token, info); } } else { log.debug("Using cached authentication info [{}] to perform credentials matching.", info); } if (info != null) { // 進(jìn)行密碼匹配 assertCredentialsMatch(token, info); } else { log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token); } return info; }
我們進(jìn)入到 assertCredentialsMatch() 方法看下它是如何實(shí)現(xiàn)的,首先獲取一個 CredentialsMatcher 對象,翻譯成漢語就是憑證匹配器,這個類的作用就是將用戶輸入的密碼以某種方式計(jì)算加密。之后會調(diào)用 doCredentialsMatch() 方法。
protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException { CredentialsMatcher cm = getCredentialsMatcher(); if (cm != null) { if (!cm.doCredentialsMatch(token, info)) { //not successful - throw an exception to indicate this: String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials."; throw new IncorrectCredentialsException(msg); } } else { throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify " + "credentials during authentication. If you do not wish for credentials to be examined, you " + "can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance."); } }
我們進(jìn)入到 doCredentialsMatch() 方法,我們可以看到,這里用 equals 方法對 token 中加密的密碼和從數(shù)據(jù)中取出來的 info 中的密碼進(jìn)行對比,若相同則返回 true ,失敗就返回 false ,并拋出 AuthenticationException ,并將 info 返回到 defaultSecurityManager 中。
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { Object tokenHashedCredentials = hashProvidedCredentials(token, info); Object accountCredentials = getCredentials(info); return equals(tokenHashedCredentials, accountCredentials); }
三、常見異常
1、DisabledAccountException:禁用的賬號
2、LockedAccountException:鎖定的賬號
3、UnknownAccountException:錯誤的賬號
4、ExcessiveAttemptsException:登錄失敗次數(shù)過多
5、IncorrectCredentialsException:錯誤的憑證
6、ExpiredCredentialsException:過期的憑證
到此這篇關(guān)于shiro 認(rèn)證的文章就介紹到這了,更多相關(guān)shiro 認(rèn)證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring中的FactoryBean與BeanFactory詳細(xì)解析
這篇文章主要介紹了Spring中的FactoryBean與BeanFactory詳細(xì)解析,在Spring框架中,FactoryBean和BeanFactory是兩個關(guān)鍵的接口,用于創(chuàng)建和管理對象實(shí)例,它們在Spring的IoC(Inversion of Control,控制反轉(zhuǎn))容器中發(fā)揮著重要的作用,需要的朋友可以參考下2023-11-11Springboot文件上傳出現(xiàn)找不到指定系統(tǒng)路徑的解決
這篇文章主要介紹了Springboot文件上傳出現(xiàn)找不到指定系統(tǒng)路徑的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08Java用20行代碼實(shí)現(xiàn)抖音小視頻批量轉(zhuǎn)換為gif動態(tài)圖
這篇文章主要介紹了Java用20行代碼實(shí)現(xiàn)抖音小視頻批量轉(zhuǎn)換為gif動態(tài)圖,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04SpringBoot詳解自定義Stater的應(yīng)用
Springboot的出現(xiàn)極大的簡化了開發(fā)人員的配置,而這之中的一大利器便是springboot的starter,starter是springboot的核心組成部分,springboot官方同時也為開發(fā)人員封裝了各種各樣方便好用的starter模塊2022-07-07Java 策略模式與模板方法模式相關(guān)總結(jié)
這篇文章主要介紹了Java 策略模式與模板方法模式相關(guān)總結(jié),幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2021-01-01Java Swing組件布局管理器之FlowLayout(流式布局)入門教程
這篇文章主要介紹了Java Swing組件布局管理器之FlowLayout(流式布局),結(jié)合實(shí)例形式分析了Swing組件布局管理器FlowLayout流式布局的常用方法及相關(guān)使用技巧,需要的朋友可以參考下2017-11-11Spring MVC---數(shù)據(jù)綁定和表單標(biāo)簽詳解
本篇文章主要介紹了Spring MVC---數(shù)據(jù)綁定和表單標(biāo)簽詳解,具有一定的參考價值,有興趣的可以了解一下。2017-01-01SpringBoot實(shí)現(xiàn)簡單的登錄注冊的項(xiàng)目實(shí)戰(zhàn)
本文主要介紹了SpringBoot實(shí)現(xiàn)簡單的登錄注冊的項(xiàng)目實(shí)戰(zhàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03Java實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)IO版本
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)IO版本,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-04-04