欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久

打開(kāi)APP
userphoto
未登錄

開(kāi)通VIP,暢享免費電子書(shū)等14項超值服

開(kāi)通VIP
源碼分析shiro認證授權流程

1. shiro介紹

Apache Shiro是一個(gè)強大易用的Java安全框架,提供了認證、授權、加密和會(huì )話(huà)管理等功能: 

  • 認證 - 用戶(hù)身份識別,常被稱(chēng)為用戶(hù)“登錄”;
  • 授權 - 訪(fǎng)問(wèn)控制;
  • 密碼加密 - 保護或隱藏數據防止被偷窺;
  • 會(huì )話(huà)管理 - 每用戶(hù)相關(guān)的時(shí)間敏感的狀態(tài)。

對于任何一個(gè)應用程序,Shiro都可以提供全面的安全管理服務(wù)。并且相對于其他安全框架,Shiro要簡(jiǎn)單的多。

2. shiro源碼概況

    先要了解shiro的基本框架(見(jiàn)http://www.cnblogs.com/davidwang456/p/4425145.html)。

    然后看一下各個(gè)組件之間的關(guān)系:

一下內容參考:http://kdboy.iteye.com/blog/1154644

Subject:即“當前操作用戶(hù)”。但是,在Shiro中,Subject這一概念并不僅僅指人,也可以是第三方進(jìn)程、后臺帳戶(hù)(Daemon Account)或其他類(lèi)似事物。它僅僅意味著(zhù)“當前跟軟件交互的東西”。但考慮到大多數目的和用途,你可以把它認為是Shiro的“用戶(hù)”概念。 
Subject代表了當前用戶(hù)的安全操作,SecurityManager則管理所有用戶(hù)的安全操作。 

SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通過(guò)SecurityManager來(lái)管理內部組件實(shí)例,并通過(guò)它來(lái)提供安全管理的各種服務(wù)。 

Realm: Realm充當了Shiro與應用安全數據間的“橋梁”或者“連接器”。也就是說(shuō),當對用戶(hù)執行認證(登錄)和授權(訪(fǎng)問(wèn)控制)驗證時(shí),Shiro會(huì )從應用配置的Realm中查找用戶(hù)及其權限信息。 
從這個(gè)意義上講,Realm實(shí)質(zhì)上是一個(gè)安全相關(guān)的DAO:它封裝了數據源的連接細節,并在需要時(shí)將相關(guān)數據提供給Shiro。當配置Shiro時(shí),你必須至少指定一個(gè)Realm,用于認證和(或)授權。配置多個(gè)Realm是可以的,但是至少需要一個(gè)。 
Shiro內置了可以連接大量安全數據源(又名目錄)的Realm,如LDAP、關(guān)系數據庫(JDBC)、類(lèi)似INI的文本配置資源以及屬性文件等。如果缺省的Realm不能滿(mǎn)足需求,你還可以插入代表自定義數據源的自己的Realm實(shí)現。

Shiro主要組件還包括: 
Authenticator :認證就是核實(shí)用戶(hù)身份的過(guò)程。這個(gè)過(guò)程的常見(jiàn)例子是大家都熟悉的“用戶(hù)/密碼”組合。多數用戶(hù)在登錄軟件系統時(shí),通常提供自己的用戶(hù)名(當事人)和支持他們的密碼(證書(shū))。如果存儲在系統中的密碼(或密碼表示)與用戶(hù)提供的匹配,他們就被認為通過(guò)認證。 
Authorizer :授權實(shí)質(zhì)上就是訪(fǎng)問(wèn)控制 - 控制用戶(hù)能夠訪(fǎng)問(wèn)應用中的哪些內容,比如資源、Web頁(yè)面等等。 
SessionManager :在安全框架領(lǐng)域,Apache Shiro提供了一些獨特的東西:可在任何應用或架構層一致地使用Session API。即,Shiro為任何應用提供了一個(gè)會(huì )話(huà)編程范式 - 從小型后臺獨立應用到大型集群Web應用。這意味著(zhù),那些希望使用會(huì )話(huà)的應用開(kāi)發(fā)者,不必被迫使用Servlet或EJB容器了?;蛘?,如果正在使用這些容器,開(kāi)發(fā)者現在也可以選擇使用在任何層統一一致的會(huì )話(huà)API,取代Servlet或EJB機制。 
CacheManager :對Shiro的其他組件提供緩存支持。 

3. 做一個(gè)demo,跑shiro的源碼,從login開(kāi)始:

第一步:用戶(hù)根據表單信息填寫(xiě)用戶(hù)名和密碼,然后調用登陸按鈕。內部執行如下:

    UsernamePasswordToken token = new UsernamePasswordToken(loginForm.getUsername(), loginForm.getPassphrase());    token.setRememberMe(true);    Subject currentUser = SecurityUtils.getSubject();    currentUser.login(token);

第二步:代理DelegatingSubject繼承Subject執行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;        }    }

第三步:調用DefaultSecurityManager繼承SessionsSecurityManager執行login方法

    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;    }

第四步:認證管理器AuthenticatingSecurityManager繼承RealmSecurityManager執行authenticate方法:

    /**     * Delegates to the wrapped {@link org.apache.shiro.authc.Authenticator Authenticator} for authentication.     */    public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {        return this.authenticator.authenticate(token);    }

第五步:抽象認證管理器AbstractAuthenticator繼承Authenticator, LogoutAware 執行authenticate方法:

public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {        if (token == null) {            throw new IllegalArgumentException("Method argumet (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);            }            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;    }

第六步:ModularRealmAuthenticator繼承AbstractAuthenticator執行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);        }    }

接著(zhù)調用:

    /**     * Performs the authentication attempt by interacting with the single configured realm, which is significantly     * simpler than performing multi-realm logic.     *     * @param realm the realm to consult for AuthenticationInfo.     * @param token the submitted AuthenticationToken representing the subject's (user's) log-in principals and credentials.     * @return the AuthenticationInfo associated with the user account corresponding to the specified {@code token}     */    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;    }

第七步:AuthenticatingRealm繼承CachingRealm執行g(shù)etAuthenticationInfo方法

   public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {        AuthenticationInfo info = getCachedAuthenticationInfo(token); //從緩存中讀取        if (info == null) {            //otherwise not cached, perform the lookup:            info = doGetAuthenticationInfo(token);  //緩存中讀不到,則到數據庫或者ldap或者jndi等去讀            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;    }

1. 從緩存中讀取的方法:

    /**     * Checks to see if the authenticationCache class attribute is null, and if so, attempts to acquire one from     * any configured {@link #getCacheManager() cacheManager}.  If one is acquired, it is set as the class attribute.     * The class attribute is then returned.     *     * @return an available cache instance to be used for authentication caching or {@code null} if one is not available.     * @since 1.2     */    private Cache<Object, AuthenticationInfo> getAuthenticationCacheLazy() {        if (this.authenticationCache == null) {            log.trace("No authenticationCache instance set.  Checking for a cacheManager...");            CacheManager cacheManager = getCacheManager();            if (cacheManager != null) {                String cacheName = getAuthenticationCacheName();                log.debug("CacheManager [{}] configured.  Building authentication cache '{}'", cacheManager, cacheName);                this.authenticationCache = cacheManager.getCache(cacheName);            }        }        return this.authenticationCache;    }

2. 從數據庫中讀取的方法:

JdbcRealm繼承 AuthorizingRealm執行doGetAuthenticationInfo方法

 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {        UsernamePasswordToken upToken = (UsernamePasswordToken) token;        String username = upToken.getUsername();        // Null username is invalid        if (username == null) {            throw new AccountException("Null usernames are not allowed by this realm.");        }        Connection conn = null;        SimpleAuthenticationInfo info = null;        try {            conn = dataSource.getConnection();            String password = null;            String salt = null;            switch (saltStyle) {            case NO_SALT:                password = getPasswordForUser(conn, username)[0];                break;            case CRYPT:                // TODO: separate password and hash from getPasswordForUser[0]                throw new ConfigurationException("Not implemented yet");                //break;            case COLUMN:                String[] queryResults = getPasswordForUser(conn, username);                password = queryResults[0];                salt = queryResults[1];                break;            case EXTERNAL:                password = getPasswordForUser(conn, username)[0];                salt = getSaltForUser(username);            }            if (password == null) {                throw new UnknownAccountException("No account found for user [" + username + "]");            }            info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());                        if (salt != null) {                info.setCredentialsSalt(ByteSource.Util.bytes(salt));            }        } catch (SQLException e) {            final String message = "There was a SQL error while authenticating user [" + username + "]";            if (log.isErrorEnabled()) {                log.error(message, e);            }            // Rethrow any SQL errors as an authentication exception            throw new AuthenticationException(message, e);        } finally {            JdbcUtils.closeConnection(conn);        }        return info;    }

接著(zhù)調用sql語(yǔ)句:

 private String[] getPasswordForUser(Connection conn, String username) throws SQLException {        String[] result;        boolean returningSeparatedSalt = false;        switch (saltStyle) {        case NO_SALT:        case CRYPT:        case EXTERNAL:            result = new String[1];            break;        default:            result = new String[2];            returningSeparatedSalt = true;        }                PreparedStatement ps = null;        ResultSet rs = null;        try {            ps = conn.prepareStatement(authenticationQuery);            ps.setString(1, username);            // Execute query            rs = ps.executeQuery();            // Loop over results - although we are only expecting one result, since usernames should be unique            boolean foundResult = false;            while (rs.next()) {                // Check to ensure only one row is processed                if (foundResult) {                    throw new AuthenticationException("More than one user row found for user [" + username + "]. Usernames must be unique.");                }                result[0] = rs.getString(1);                if (returningSeparatedSalt) {                    result[1] = rs.getString(2);                }                foundResult = true;            }        } finally {            JdbcUtils.closeResultSet(rs);            JdbcUtils.closeStatement(ps);        }        return result;    }

其中authenticationQuery定義如下:

 protected String authenticationQuery = DEFAULT_AUTHENTICATION_QUERY; protected static final String DEFAULT_AUTHENTICATION_QUERY = "select password from users where username = ?";

4. 小結

Apache Shiro 是功能強大并且容易集成的開(kāi)源權限框架,它能夠完成認證、授權、加密、會(huì )話(huà)管理等功能。認證和授權為權限控制的核心,簡(jiǎn)單來(lái)說(shuō),“認證”就是證明你是誰(shuí)? Web 應用程序一般做法通過(guò)表單提交用戶(hù)名及密碼達到認證目的?!笆跈唷奔词欠裨试S已認證用戶(hù)訪(fǎng)問(wèn)受保護資源。

參考文獻:

http://kdboy.iteye.com/blog/1154644

http://www.ibm.com/developerworks/cn/java/j-lo-shiro/ 

 

本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請點(diǎn)擊舉報。
打開(kāi)APP,閱讀全文并永久保存 查看更多類(lèi)似文章
猜你喜歡
類(lèi)似文章
第四章:Shiro的身份認證(Authentication)
第二章 身份驗證
shiro實(shí)現不同身份使用不同Realm進(jìn)行驗證
初識Shiro
Shiro —— Spring 環(huán)境下的使用
Apache Shiro 驗證
更多類(lèi)似文章 >>
生活服務(wù)
分享 收藏 導長(cháng)圖 關(guān)注 下載文章
綁定賬號成功
后續可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服

欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久