欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

shiro 認(rèn)證流程操作

 更新時間:2024年01月09日 15:11:01   作者:快樂的小三菊  
這篇文章主要介紹了shiro 認(rèn)證操作的相關(guān)資料,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧

一、背景

       我們可以使用 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)文章

最新評論