shiro登录模块源码分析

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了shiro登录模块源码分析相关的知识,希望对你有一定的参考价值。

接触和使用shiro还是有好大一段时间,可惜并没有搞明白其实的原理和机制。因为工作中使用的框架都封装好了,so......并没有去研究。

原来一直猜想的是shiro可以直接连接数据库,验证用户名和密码。但是又没在实体类中找到有什么特殊的标记注解之类的。

就有点好奇了,于是趁这两天工作不是那么紧张了,就跟了下源码。

如有不对,请留言指正。蟹蟹!

 

红色部分是主要代码;
 
UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), password, rememberMe.equals("0") ? false : true);
Subject currentUser = AppUtils.getSubject();
try {
    currentUser.login(token);
} catch (AuthenticationException e) {
    token.clear();
    model.addAttribute("user_err", "用户名或密码错误");
    return loginUrl;
}
 
将登录委托给subjectManager
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;
    }
}
 
subjectManager调authenticate模块进行身份认证
 
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;
}
 
 
public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
    return this.authenticator.authenticate(token);
}
 
 
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) {......
 
 
判断Realm是否有实现类
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
    assertRealmsConfigured();
    //配置文件中注入了bean
    Collection<Realm> realms = getRealms();
    if (realms.size() == 1) {
        return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
    } else {
//这一步还不清楚
        return doMultiRealmAuthentication(realms, authenticationToken);
    }
}
 
调用重写的登录方法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;
}

 

最后调用自己实现的用户名密码验证

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) {
    UsernamePasswordToken upToken = (UsernamePasswordToken) arg0;
    String password = String.valueOf(upToken.getPassword());
    SysUserMember us = sysUserRepository.doGetAuthenticationInfoAvailable(upToken.getUsername());
    if (us == null) {
        throw new AuthenticationException("查询无此用户.");
    } else if (StringUtils.isBlank(us.getUserName()) || StringUtils.isBlank(us.getUserPassword())) {
        throw new AuthenticationException("查询无此用户.");
    } else if (!us.getUserPassword().equals(password)) {
        throw new AuthenticationException("用户名或密码错误.");
    } else {
        SecurityUtils.getSubject().getSession().setAttribute(AppConfig.SESSION_KEY, us);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(us.getUserName(), us.getUserPassword(), getName());
        return info;
    }
}

以上是关于shiro登录模块源码分析的主要内容,如果未能解决你的问题,请参考以下文章

Shiro源码分析----认证流程

Shiro源码分析-ShiroFilterFactoryBean

shiro源码分析-授权过程

源码分析 shiro注解授权

shiro源码分析2

Shiro的Filter机制详解---源码分析