shiro 認證流程操作
一、背景
我們可以使用 shiro 進行認證操作,下面粘貼的是 LoginController 的代碼,模擬用戶登錄的請求操作:
@Controller
@Slf4j
public class LoginController {
@RequestMapping("/login")
public String login(User user) {
if (StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())) {
return "error";
}
//用戶認證信息
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
user.getUserName(),
user.getPassword());
usernamePasswordToken.setRememberMe(true);
try {
//進行驗證,這里可以捕獲異常,然后返回對應信息
subject.login(usernamePasswordToken);
} catch (UnknownAccountException e) {
log.error("用戶名不存在!", e);
return "error";
} catch (AuthenticationException e) {
log.error("賬號或密碼錯誤!", e);
return "error";
} catch (AuthorizationException e) {
log.error("沒有權限!", e);
return "error";
}
return "shiro_index";
}
}二、源碼追蹤分析
我們先獲取用戶輸入的 userName 和 passWord ,然后將 userName 和 passWord 這兩個參數傳入到 UsernamePasswordToken 中獲取 token 對象,最后調用SecurityUtils.getSubject() 的 login() 方法將 token 傳入做系統(tǒng)校驗。
我們進入源碼查看下 login() 方法底層是如何實現的,可以看到主要還是調用了 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ù)進入源碼查看 securityManager 安全管理器的 login() 方法是如何實現的,可以看到在這個方法中定義了 AuthenticationInfo 對象來接收從 Relam 傳來的認證信息。
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ù)進入源碼查看 authenticate() 方法是如何實現的,我們發(fā)現這個方法內部調用了 authenticator 對象的 authenticate() 方法。
public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
return this.authenticator.authenticate(token);
}我們繼續(xù)進入源碼查看 authenticator 對象的 authenticate() 方法是如何實現的。我們發(fā)現在這個方法的內部調用了 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ù)進入源碼查看 doAuthenticate() 方法是如何實現的。我們發(fā)現在這個方法的內部調用了 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 是否存在,若不存在就會拋出異常,它會根據 relam 的個數來判斷執(zhí)行哪個方法,我在上一篇文章中只定義了一個 relam ,所以它會執(zhí)行 doSingleRealmAuthentication() 這個方法,并且會將 relam 和 token 傳入進去。
我們繼續(xù)進入源碼查看 doSingleRealmAuthentication() 方法是如何實現的, 我們可以看到,在這里它會先判斷 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ù)進入源碼查看 getAuthenticationInfo() 方法是如何實現的, getCachedAuthenticationInfo() 方法是從 shiro 緩存中讀取用戶信息,如果沒有,才會從 relam 中獲取,如果是第一次登錄,緩存中指定沒有我們的認證信息,所以會執(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ù)進入源碼查看 doGetAuthenticationInfo() 方法是如何實現的,我們發(fā)現其實現類有如下幾個,其中 CustomRealm 就是我們自定義實現的。

我們再來看一下,我們自定義的 CustomRealm 中的 doGetAuthenticationInfo() 代碼 ,這個方法就是需要查詢數據庫中的數據并進行一個簡單的校驗,最后封裝成 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();
}
// 若存在將此用戶存放到登錄認證info中,無需做密碼比對shiro會為我們進行密碼比對校驗
if(user !=null && user.getStatus().equals("1")){
ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUserName()+ "salt");
/** 這里驗證authenticationToken和simpleAuthenticationInfo的信息,構造方法支持三個或者四個參數,
* 第一個參數傳入userName或者是user對象都可以。
* 第二個參數傳入數據庫中該用戶的密碼(記得是加密后的密碼)
* 第三個參數傳入加密的鹽值,若沒有則可以不加
* 第四個參數傳入當前Relam的名字
**/
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, user.getPassword().toString(),credentialsSalt, getName());
return simpleAuthenticationInfo;
}
return null;
}截至到目前為止,我們算是獲取到了認證信息了,接下來就是看下 shiro 是怎么進行認證的,我們返回去再看下 AuthenticatingRealm 類的 getAuthenticationInfo() 方法,我們可以看到,獲取完信息之后就需要進行密碼匹配,會調用 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) {
// 進行密碼匹配
assertCredentialsMatch(token, info);
} else {
log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token);
}
return info;
}我們進入到 assertCredentialsMatch() 方法看下它是如何實現的,首先獲取一個 CredentialsMatcher 對象,翻譯成漢語就是憑證匹配器,這個類的作用就是將用戶輸入的密碼以某種方式計算加密。之后會調用 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.");
}
}我們進入到 doCredentialsMatch() 方法,我們可以看到,這里用 equals 方法對 token 中加密的密碼和從數據中取出來的 info 中的密碼進行對比,若相同則返回 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:登錄失敗次數過多
5、IncorrectCredentialsException:錯誤的憑證
6、ExpiredCredentialsException:過期的憑證
到此這篇關于shiro 認證的文章就介紹到這了,更多相關shiro 認證內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring中的FactoryBean與BeanFactory詳細解析
這篇文章主要介紹了Spring中的FactoryBean與BeanFactory詳細解析,在Spring框架中,FactoryBean和BeanFactory是兩個關鍵的接口,用于創(chuàng)建和管理對象實例,它們在Spring的IoC(Inversion of Control,控制反轉)容器中發(fā)揮著重要的作用,需要的朋友可以參考下2023-11-11
Springboot文件上傳出現找不到指定系統(tǒng)路徑的解決
這篇文章主要介紹了Springboot文件上傳出現找不到指定系統(tǒng)路徑的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Java用20行代碼實現抖音小視頻批量轉換為gif動態(tài)圖
這篇文章主要介紹了Java用20行代碼實現抖音小視頻批量轉換為gif動態(tài)圖,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04
Java Swing組件布局管理器之FlowLayout(流式布局)入門教程
這篇文章主要介紹了Java Swing組件布局管理器之FlowLayout(流式布局),結合實例形式分析了Swing組件布局管理器FlowLayout流式布局的常用方法及相關使用技巧,需要的朋友可以參考下2017-11-11
SpringBoot實現簡單的登錄注冊的項目實戰(zhàn)
本文主要介紹了SpringBoot實現簡單的登錄注冊的項目實戰(zhàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03

