设为首页 收藏本站
查看: 5979|回复: 1

[经验分享] Apache Shiro学习笔记(二)身份验证subject.login过程

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2016-7-27 10:44:36 | 显示全部楼层 |阅读模式
subject.login(token);

  • DelegatingSubject类的login方法


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package org.apache.shiro.subject.support;

public class DelegatingSubject implements Subject {

    protected PrincipalCollection principals;
    protected boolean authenticated;
    protected String host;
    protected Session session;

    public void login(AuthenticationToken token) throws AuthenticationException {
        // 清除RunAs的身份信息
        clearRunAsIdentitiesInternal();
        /* 通过securityManager实现真正的登录,并返回登录之后的主体(subject)数据 */
        Subject subject = securityManager.login(this, token);

        PrincipalCollection principals;

        // 通过subject获取身份信息,略

        this.principals = principals;
        this.authenticated = true;
        // 部分代码略
    }

    public boolean isAuthenticated() {
        return authenticated;
    }
}




  • DefaultSecurityManager类的login方法

wKioL1eWzy2hDXPuAAO-8Rda_B8458.jpg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package org.apache.shiro.mgt;

public class DefaultSecurityManager extends SessionsSecurityManager {

    /**
     * 如果登录失败会抛出异常,如果成功会返回代表身份信息的subject
     */
    public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
        AuthenticationInfo info;
        try {
            info = authenticate(token);
        } catch (AuthenticationException ae) {
            // 认证失败,抛出异常
        }

        Subject loggedIn = createSubject(token, info, subject);

        onSuccessfulLogin(token, info, loggedIn);

        return loggedIn;
    }
}




  • AuthenticatingSecurityManager类的authenticate(token)方法

wKioL1eWzpWR6ftcAAJONmD4F2k830.jpg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package org.apache.shiro.mgt;

public abstract class AuthenticatingSecurityManager extends RealmSecurityManager {
    // org.apache.shiro.authc.Authenticator的职责是验证用户帐号,
    // 是Shiro API中身份验证核心的入口点:就一个authenticate方法。
    private Authenticator authenticator;

    // org.apache.shiro.authc.pam.ModularRealmAuthenticator
    public AuthenticatingSecurityManager() {
        super();
        this.authenticator = new ModularRealmAuthenticator();
    }

    /*
     * 调用ModularRealmAuthenticator的authenticate,而ModularRealmAuthenticator无该方法
     * 因此调用该类的父类AbstractAuthenticator的authenticate方法
     */
    public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
        return this.authenticator.authenticate(token);
    }
}




  • AbstractAuthenticator的authenticate方法


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package org.apache.shiro.authc;

public abstract class AbstractAuthenticator implements Authenticator, LogoutAware {
     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) {
                // 认证失败,抛出异常
                throw new AuthenticationException(msg);
            }
        } catch (Throwable t) {
            // 认证失败,抛出异常
        }

        log.debug("Authentication successful for token [{}].  Returned account [{}]", token, info);

        notifySuccess(token, info);

        return info;
    }
    // 抽象方法,调用子类ModularRealmAuthenticator的实现
    protected abstract AuthenticationInfo doAuthenticate(AuthenticationToken token)
            throws AuthenticationException;
}




  • ModularRealmAuthenticator类的doAuthenticate方法


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package org.apache.shiro.authc.pam;

public class ModularRealmAuthenticator extends AbstractAuthenticator {
    /**
     * List of realms that will be iterated through when a user authenticates.
     */
    private Collection<Realm> realms;

    /**
     * 认证策略, 默认org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy
     */
    private AuthenticationStrategy authenticationStrategy;

    /* 默认无参构造方法 */
    public ModularRealmAuthenticator() {
        this.authenticationStrategy = new AtLeastOneSuccessfulStrategy();
    }

    /* 执行认证 */
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        assertRealmsConfigured();
        Collection<Realm> realms = getRealms();
        if (realms.size() == 1) {
            // 最终调用AuthenticationInfo info = realm.getAuthenticationInfo(token);
            return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
        } else {
            // 最终调用AuthenticationInfo info = realm.getAuthenticationInfo(token);
            return doMultiRealmAuthentication(realms, authenticationToken);
        }
    }
}




  • 调用AuthenticatingRealm类的getAuthenticationInfo


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package org.apache.shiro.realm;

public abstract class AuthenticatingRealm extends CachingRealm implements Initializable {
    /**
     * Credentials matcher used to determine if the provided credentials match the credentials stored in the data store.
     */
    private CredentialsMatcher credentialsMatcher;

        /*-------------------------------------------
    |         C O N S T R U C T O R S           |
    ============================================*/
    public AuthenticatingRealm() {
        this(null, new SimpleCredentialsMatcher());
    }

    public AuthenticatingRealm(CacheManager cacheManager) {
        this(cacheManager, new SimpleCredentialsMatcher());
    }

    public AuthenticatingRealm(CredentialsMatcher matcher) {
        this(null, matcher);
    }

    public AuthenticatingRealm(CacheManager cacheManager, CredentialsMatcher matcher) {
        authenticationTokenClass = UsernamePasswordToken.class;
        // 代码略
    }

    /* 获取认证信息,只有AuthenticatingRealm类实现了该方法 */
    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) {
            // 比较传入的token和doGetAuthenticationInfo获取到的值是否一样;
            // info实际上是调用doGetAuthenticationInfo方法返回的,一般是自定义doGetAuthenticationInfo方法来处理认证。
            assertCredentialsMatch(token, info);   
        } else {
            log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}].  Returning null.", token);
        }

        return info;
    }

    /* Retrieves authentication data from an implementation-specific datasource (RDBMS, LDAP, etc) for the given
     * authentication token.
     * 用户自定义的Realm一般都实现该方法,用来实现自己的身份认证(如根据用户名查询用户是否存在,若存在进行密码比对)
     */
    protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
}



实际上在ModularRealmAuthenticator中获取到的Realm是IniRealm,而继承关系为:
1
2
3
4
5
org.apache.shiro.realm.text.IniRealm
    extends org.apache.shiro.realm.text.TextConfigurationRealm
        extends org.apache.shiro.realm.SimpleAccountRealm
            extends org.apache.shiro.realm.AuthorizingRealm
                extends org.apache.shiro.realm.AuthenticatingRealm



在IniRealm的实例中调用getAuthenticationInfo时,实际调用的是父类AuthenticatingRealm的getAuthenticationInfo方法,而doGetAuthenticationInfo方法在子类中有自己的实现。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package org.apache.shiro.realm.text;

public class IniRealm extends TextConfigurationRealm {

    public static final String USERS_SECTION_NAME = "users";
    public static final String ROLES_SECTION_NAME = "roles";

    private static transient final Logger log = LoggerFactory.getLogger(IniRealm.class);

    private String resourcePath;
    private Ini ini; //reference added in 1.2 for SHIRO-322

    public IniRealm() {
        super();
    }

    /* SecurityManager中的createRealm中会调用该构造函数创建实例 */
    public IniRealm(Ini ini) {
        this();
        processDefinitions(ini);
    }

     private void processDefinitions(Ini ini) {
        /* 处理ini文件中的[roles]定义 */
        Ini.Section rolesSection = ini.getSection(ROLES_SECTION_NAME);
        if (!CollectionUtils.isEmpty(rolesSection)) {
            log.debug("Discovered the [{}] section.  Processing...", ROLES_SECTION_NAME);
            processRoleDefinitions(rolesSection);
        }
        /* 处理ini文件中的[users]定义 */
        Ini.Section usersSection = ini.getSection(USERS_SECTION_NAME);
        if (!CollectionUtils.isEmpty(usersSection)) {
            log.debug("Discovered the [{}] section.  Processing...", USERS_SECTION_NAME);
            /*
            * 在该方法中会执行new SimpleAccount(username, password, getName());
            * SimpleAccount构造方法:public SimpleAccount(Object principal, Object credentials, String realmName) {......}
            */
            processUserDefinitions(usersSection);
        }
     }
}



  • IniRealm中未定义doGetAuthenticationInfo的实现,会自动调用其父类SimpleAccountRealm的实现


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package org.apache.shiro.realm;
/**
* User accounts and roles are stored in two Maps in memory,
* so it is expected that the total number of either is not sufficiently large.
*/
public class SimpleAccountRealm extends AuthorizingRealm {
    protected final Map<String, SimpleAccount> users; //username-to-SimpleAccount
    protected final Map<String, SimpleRole> roles; //roleName-to-SimpleRole
    protected final ReadWriteLock USERS_LOCK;
    protected final ReadWriteLock ROLES_LOCK;

    public SimpleAccountRealm() {
        this.users = new LinkedHashMap<String, SimpleAccount>();
        this.roles = new LinkedHashMap<String, SimpleRole>();
        USERS_LOCK = new ReentrantReadWriteLock();
        ROLES_LOCK = new ReentrantReadWriteLock();
        //SimpleAccountRealms are memory-only realms - no need for an additional cache mechanism since we're
        //already as memory-efficient as we can be:
        setCachingEnabled(false);
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;

        // getUser就是从IniRealm的processUserDefinitions方法处理时,调用SimpleAccountRealm.add添加的Account
        SimpleAccount account = getUser(upToken.getUsername());

        // 略

        return account;
    }
}



总结,至此,身份认证完成(具体的比对token的工作由AuthenticatingRealm.assertCredentialsMatch(token,  info);完成)。



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-250173-1-1.html 上篇帖子: Ubuntu下Apache配置与详解 下篇帖子: 基于apache的svn服务器搭建

尚未签到

发表于 2017-12-13 17:01:09 | 显示全部楼层
你好问一下,subject.login(token);登录信息保存到subject里面我要怎么取?

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表