詳解shrio的認(rèn)證(登錄)過程
shrio是一個比較輕量級的安全框架,主要的作用是在后端承擔(dān)認(rèn)證和授權(quán)的工作。今天就講一下shrio進(jìn)行認(rèn)證的一個過程。
首先先介紹一下在認(rèn)證過程中的幾個關(guān)鍵的對象:
- Subject:主體
訪問系統(tǒng)的用戶,主體可以是用戶、程序等,進(jìn)行認(rèn)證的都稱為主體;
- Principal:身份信息
是主體(subject)進(jìn)行身份認(rèn)證的標(biāo)識,標(biāo)識必須具有唯一性,如用戶名、手機(jī)號、郵箱地址等,一個主體可以有多個身份,但是必須有一個主身份(Primary Principal)。
- credential:憑證信息
是只有主體自己知道的安全信息,如密碼、證書等。
接著我們就進(jìn)入認(rèn)證的具體過程:
首先是從前端的登錄表單中接收到用戶輸入的token(username + password):
@RequestMapping("/login")
public String login(@RequestBody Map user){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.get("email").toString(), user.get("password").toString());
try {
subject.login(usernamePasswordToken);
} catch (UnknownAccountException e) {
return "郵箱不存在!";
} catch (AuthenticationException e) {
return "賬號或密碼錯誤!";
}
return "登錄成功!";
}
這里的usernamePasswordToken(以下簡稱token)就是用戶名和密碼的一個結(jié)合對象,然后調(diào)用subject的login方法將token傳入開始認(rèn)證過程。
接著會發(fā)現(xiàn)subject的login方法調(diào)用的其實(shí)是securityManager的login方法:
Subject subject = securityManager.login(this, token);
再往下看securityManager的login方法內(nèi)部:
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;
}
上面代碼的關(guān)鍵在于:
info = authenticate(token);
即將token傳入authenticate方法中得到一個AuthenticationInfo類型的認(rèn)證信息。
以下是authenticate方法的具體內(nèi)容:
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;
}
首先就是判斷token是否為空,不為空再將token傳入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);
}
}
這一步是判斷是有單個Reaml驗(yàn)證還是多個Reaml驗(yàn)證,單個就執(zhí)行doSingleRealmAuthentication()方法,多個就執(zhí)行doMultiRealmAuthentication()方法。
一般情況下是單個驗(yàn)證:
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;
}
這一步中首先判斷是否支持Realm,只有支持Realm才調(diào)用realm.getAuthenticationInfo(token)獲取info。
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;
}
首先查看Cache中是否有該token的info,如果有,則直接從Cache中去即可。如果是第一次登錄,則Cache中不會有該token的info,需要調(diào)用doGetAuthenticationInfo(token)方法獲取,并將結(jié)果加入到Cache中,方便下次使用。而這里調(diào)用的doGetAuthenticationInfo()方法就是我們在自己重寫的方法,具體的內(nèi)容是自定義了對拿到的這個token的一個處理的過程:
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
if (authenticationToken.getPrincipal() == null)
return null;
String email = authenticationToken.getPrincipal().toString();
User user = userService.findByEmail(email);
if (user == null)
return null;
else return new SimpleAuthenticationInfo(email, user.getPassword(), getName());
}
這其中進(jìn)行了幾步判斷:首先是判斷傳入的用戶名是否為空,在判斷傳入的用戶名在本地的數(shù)據(jù)庫中是否存在,不存在則返回一個用戶名不存在的Exception。以上兩部通過之后生成一個包括傳入用戶名和密碼的info,注意此時關(guān)于用戶名的驗(yàn)證已經(jīng)完成,接下來進(jìn)入對密碼的驗(yàn)證。
將這一步得到的info返回給getAuthenticationInfo方法中的
assertCredentialsMatch(token, info);
此時的info是正確的用戶名和密碼的信息,token是輸入的用戶名和密碼的信息,經(jīng)過前面步驟的驗(yàn)證過程,用戶名此時已經(jīng)是真是存在的了,這一步就是驗(yàn)證輸入的用戶名和密碼的對應(yīng)關(guān)系是否正確。
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.");
}
}
上面步驟就是驗(yàn)證token中的密碼的和info中的密碼是否對應(yīng)的代碼。這一步驗(yàn)證完成之后,整個shrio認(rèn)證的過程就結(jié)束了。
以上就是詳解shrio的認(rèn)證(登錄)過程的詳細(xì)內(nèi)容,更多關(guān)于shrio的認(rèn)證(登錄)過程的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決Springboot @Autowired 無法注入問題
WebappApplication 一定要在包的最外層,否則Spring無法對所有的類進(jìn)行托管,會造成@Autowired 無法注入。接下來給大家介紹解決Springboot @Autowired 無法注入問題,感興趣的朋友一起看看吧2018-08-08
springboot+thymeleaf整合阿里云OOS對象存儲圖片的實(shí)現(xiàn)
本文主要介紹了springboot+thymeleaf整合阿里云OOS對象存儲圖片的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05
Java使用設(shè)計模式中迭代器模式構(gòu)建項(xiàng)目的代碼結(jié)構(gòu)示例
這篇文章主要介紹了Java使用設(shè)計模式中迭代器模式構(gòu)建項(xiàng)目的代碼結(jié)構(gòu)示例,迭代器模式能夠?qū)υL問者隱藏對象的內(nèi)部細(xì)節(jié),需要的朋友可以參考下2016-05-05
IntelliJ?IDEA無公網(wǎng)遠(yuǎn)程Linux服務(wù)器環(huán)境開發(fā)過程(推薦收藏)
下面介紹如何在IDEA中設(shè)置遠(yuǎn)程連接服務(wù)器開發(fā)環(huán)境并結(jié)合Cpolar內(nèi)網(wǎng)穿透工具實(shí)現(xiàn)無公網(wǎng)遠(yuǎn)程連接,然后實(shí)現(xiàn)遠(yuǎn)程Linux環(huán)境進(jìn)行開發(fā),感興趣的朋友跟隨小編一起看看吧2023-12-12

