美文网首页shiro
shiro的认证流程

shiro的认证流程

作者: 抓兔子的猫 | 来源:发表于2016-12-21 10:55 被阅读439次

    *以下仅是部分关键代码

    1. 应用程序根据用户的身份和凭证(principals和credentials)来构造出AuthenticationToken实例,并调用Subject.login的方法进行登录,其会自动委托给SecurityManager。
    try {
              Subject subject = SecurityUtils.getSubject();
                // 已登陆则 跳到首页
                if (subject.isAuthenticated()) {
                    return "redirect:/personal/zone";
                }
        
                // 身份验证
                String username = request.getParameter("login_username");
                String password = request.getParameter("login_password");
                subject.login(new UsernamePasswordToken(username, password));
            } catch (AuthenticationException e) {
    }
    
    1. Subject实例通常上都是DelegatingSubject(或子类),在验证开始的时候,Subject实例会将验证委托给应用程序配置的SecurityManager,并调用securityManager.login(token)方法进行身份认证。
    public class DelegatingSubject implements Subject {
     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;
            }
        }
    }
    
    1. SecurityManager得到token信息后,通过调用authenticator.authenticate(token)方法,把身份验证委托给内置的Authenticator的实例进行验证。authenticator通常是ModularRealmAuthenticator实例,支持对一个或多个Realm实例进行适配。ModularRealmAuthenticator提供了一种可插拔的认证风格,你可以在此处插入自定义Realm实现。
    public class DefaultSecurityManager extends SessionsSecurityManager {
     private Authenticator authenticator;
     public AuthenticatingSecurityManager() {
            super();
            this.authenticator = new ModularRealmAuthenticator();
        }
     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);
        }
    
    1. 如果配置了多个Realm,ModularRealmAuthenticator会根据配置的AuthenticationStrategy(身份验证策略)进行多Realm认证过程。
      注:如果应用程序中仅配置了一个Realm,Realm将被直接调用而无需再配置认证策略。
    //ModularRealmAuthenticator 继承了 AbstractAuthenticator (authenticate 调用了doAuthenticate)
    public class ModularRealmAuthenticator extends AbstractAuthenticator {
    private Collection<Realm> realms;
       public void setRealms(Collection<Realm> realms) {
            this.realms = realms;
        }
        protected Collection<Realm> getRealms() {
            return this.realms;
        }
        public ModularRealmAuthenticator() {
            this.authenticationStrategy = new AtLeastOneSuccessfulStrategy();
        }
        protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
            assertRealmsConfigured();
            Collection<Realm> realms = getRealms();
            if (realms.size() == 1) {
              //仅配置了一个realm 
                return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
            } else {
              //配置了多个realm 
                return doMultiRealmAuthentication(realms, authenticationToken);
            }
        }
    
    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) {
                    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;
        }
    protected abstract AuthenticationInfo doAuthenticate(AuthenticationToken token) throws AuthenticationException;```
    
    5.判断每个Realm是否支持提交的token,如果支持Realm就会调用getAuthenticationInfo(token)方法进行认证处理。
    
    
    protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
        //判断realm 是否支持 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时一般会继承 AuthorizingRealm,AuthorizingRealm又继承
    AuthenticatingRealm
    

    public abstract class AuthenticatingRealm extends CachingRealm implements Initializable {
    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) {
            //判断密码是否匹配,如果不匹配将抛出密码错误异常IncorrectCredentialsException;
            //另外如果密码重试此处太多将抛出超出重试次数异常ExcessiveAttemptsException;
            //在组装SimpleAuthenticationInfo信息时,需要传入:身份信息(用户名)、凭据(密文密码)、盐(username+salt),
            //CredentialsMatcher使用盐加密传入的明文密码和此处的密文密码进行匹配。
            assertCredentialsMatch(token, info);
        } else {
            log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}].  Returning null.", token);
        }
    
        return info;
    }
    

    protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
    }

    参考 http://blog.csdn.net/lishehe/article/details/45219023

    相关文章

      网友评论

        本文标题:shiro的认证流程

        本文链接:https://www.haomeiwen.com/subject/ewfqvttx.html