美文网首页
Shiro工作过程分析

Shiro工作过程分析

作者: 王兆阳 | 来源:发表于2017-05-26 17:54 被阅读0次

    Shiro的使用方法参见跟我学shiro

    Shiro的验证过程分析如下:

    获取SecurityManager 并绑定给SecurityUtils

    • 通过xml配置
    <bean id="myShiroRealm" class="com.wechat.ztsoft.shiro.realm.MyRealm">
            <!--密码匹配算法-->
            <property name="credentialsMatcher" ref="credentialsMatcher"/>
            <!--授权信息缓存-->
            <property name="authorizationCachingEnabled" value="true"/>
            <property name="authorizationCacheName" value="authorizationCache"/>
        </bean>
    <bean id="securityManager"
          class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="myShiroRealm"/>
        <property name="sessionManager" ref="sessionManager" />
        <property name="cacheManager" ref="cacheManger" />
    </bean>
    <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
        <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
            <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
            <property name="arguments" ref="securityManager"/>
        </bean>
    

    获取Subject并创建用户凭证

    • 获取Subject,SecurityUtils.getSubject
    public static Subject getSubject() {
          Subject subject = ThreadContext.getSubject();
          if (subject == null) {
              subject = (new Subject.Builder()).buildSubject();
              ThreadContext.bind(subject);
          }
          return subject;
      }
    
    • 函数内第一行函数,通过线程本地变量绑定Subject到当前线程;具体参见ThreadContext类,其定义了一个静态线程本地变量:
    private static final ThreadLocal<Map<Object, Object>> resources = new InheritableThreadLocalMap<Map<Object, Object>>();
    
    • 调用其getSubjec函数,最终调用该类内的静态函数getValue:
    public static Object get(Object key) {
            if (log.isTraceEnabled()) {
                String msg = "get() - in thread [" + Thread.currentThread().getName() + "]";
                log.trace(msg);
            }
    
            Object value = getValue(key);
            if ((value != null) && log.isTraceEnabled()) {
                String msg = "Retrieved value of type [" + value.getClass().getName() + "] for key [" +
                        key + "] " + "bound to thread [" + Thread.currentThread().getName() + "]";
                log.trace(msg);
            }
            return value;
        }
    //get内部调用了getValue函数
    private static Object getValue(Object key) {
            return resources.get().get(key);
        }
    
    • 其调用了ThreadLocal变量,然后获取其Map类型的值,然后从中获取该Key对应的对象。
      结束后回到SecurityUtils中,若该线程仍没有绑定subject,可看到会新建一个subject对象,具体创建方法为:
    subject = (new Subject.Builder()).buildSubject();
    
    • 调用绑定的securityManager对象创建subject,
    public Subject buildSubject() {
               return this.securityManager.createSubject(this.subjectContext);
           }
    
    • 绑定的SecurityManager实现类为DefaultWebSecurityManager,故调用其实现的createSubject方法创建

    public DefaultWebSecurityManager() {
    super();
    ((DefaultSubjectDAO) this.subjectDAO).setSessionStorageEvaluator(new DefaultWebSessionStorageEvaluator());
    this.sessionMode = HTTP_SESSION_MODE;
    //设置subject工厂类为DefaultWebSubjectFactory
    setSubjectFactory(new DefaultWebSubjectFactory());
    setRememberMeManager(new CookieRememberMeManager());
    setSessionManager(new ServletContainerSessionManager());
    }

    
    - DefaultWebSecurityManager类调用其父类DefaultSecurityManager实现的createSubject
    

    protected Subject createSubject(AuthenticationToken token, AuthenticationInfo info, Subject existing) {
    SubjectContext context = createSubjectContext();
    context.setAuthenticated(true);
    context.setAuthenticationToken(token);
    context.setAuthenticationInfo(info);
    if (existing != null) {
    context.setSubject(existing);
    }
    return createSubject(context);
    }

    
    - 最终调用DefaultSecurityManager的createSubject(SubjectContext subjectContext)方法
    

    public Subject createSubject(SubjectContext subjectContext) {
    //create a copy so we don't modify the argument's backing map:
    SubjectContext context = copy(subjectContext);
    context = ensureSecurityManager(context);
    context = resolveSession(context);
    context = resolvePrincipals(context);
    / /此处为关键
    Subject subject = doCreateSubject(context);
    save(subject);
    return subject;
    }

    
    - 关键创建代码调用了doCreateSubject方法
    

    protected Subject doCreateSubject(SubjectContext context) {
    return getSubjectFactory().createSubject(context);
    }

    
    - 其调用了前面设置的DefaultWebSubjectFactory工程类的createSubject方法,其返回了一个Subject的实现类WebDelegatingSubject的对象
    

    public Subject createSubject(SubjectContext context) {
    if (!(context instanceof WebSubjectContext)) {
    return super.createSubject(context);
    }
    WebSubjectContext wsc = (WebSubjectContext) context;
    SecurityManager securityManager = wsc.resolveSecurityManager();
    Session session = wsc.resolveSession();
    boolean sessionEnabled = wsc.isSessionCreationEnabled();
    PrincipalCollection principals = wsc.resolvePrincipals();
    boolean authenticated = wsc.resolveAuthenticated();
    String host = wsc.resolveHost();
    ServletRequest request = wsc.resolveServletRequest();
    ServletResponse response = wsc.resolveServletResponse();

        return new WebDelegatingSubject(principals, authenticated, host, session, sessionEnabled,
                request, response, securityManager);
    }
    
    
    
    
    - 接下来将新建的subject,绑定到线程变量中,具体方法如下:
    

    public static void bind(Subject subject) {
    if (subject != null) {
    put(SUBJECT_KEY, subject);
    }
    }
    //实际调用put方法
    public static void put(Object key, Object value) {
    if (key == null) {
    throw new IllegalArgumentException("key cannot be null");
    }

        if (value == null) {
            remove(key);
            return;
        }
        //将subject对象插入到map对象中
        resources.get().put(key, value);
    
        if (log.isTraceEnabled()) {
            String msg = "Bound value of type [" + value.getClass().getName() + "] for key [" +
                    key + "] to thread " + "[" + Thread.currentThread().getName() + "]";
            log.trace(msg);
        }
    }
    
    - 创建用户凭证
    

    UsernamePasswordToken token = new UsernamePasswordToken("wang", "123456");

    
    ### 执行登录验证
    -  调用Subject.login(token ),实际调用WebDelegatingSubject的login方法,WebDelegatingSubject未覆盖login方法,调用其父类的,即DelegatingSubject的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;
        }
    }
    
    
    - 其委托给SecurityManager执行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的authenticate方法;回去看XML配置模块,我们配置实现获取认证信息和授权信息的Realm,设置完成后调用afterRealmsSet方法,AuthenticatingSecurityManager覆盖了该方法,如下
    

    protected void afterRealmsSet() {
    super.afterRealmsSet();
    if (this.authenticator instanceof ModularRealmAuthenticator) {
    ((ModularRealmAuthenticator) this.authenticator).setRealms(getRealms());
    }
    }

    
    - 将Realm赋值给实际Authenticator,AuthenticatingSecurityManager中的Authenticator为ModularRealmAuthenticator实现类,发现Authenticator的子类AbstractAuthenticator实现了authenticate方法,并把实际执行代码用占位符doAuthenticate留待子类去实现,我们进入ModularRealmAuthenticator查看其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);
    }
    }

    
    - 可以看到分位一个或多个Realm两张情况,我们以一个Realm为例分析
    

    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);
    }
    //关键代码 通过realm获取认证信息,此处我们自己实现realm,根据逻返回认证信息类,如SimpleAuthenticationInfo
    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,其继承自AuthenticatingRealm,实现doGetAuthorizationInfo及doGetAuthenticationInfo函数
    进入AuthenticatingRealm查看其getAuthenticationInfo函数
    

    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;
    }
    
    可以看到核心既是我们需要实现的doGetAuthenticationInfo函数,获取认证信息,然后进行验证assertCredentialsMatch,使用CredentialsMatcher进行实际验证,我们可以自己实现CredentialsMatcher接口进行验证
    

    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.");
    }
    }

    
    -  贴出我自己的验证器,带防止多次试探密码的功能
    ···
    public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {
    
        private Cache<String, AtomicInteger> passwordRetryCache;
    
        public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
            passwordRetryCache = cacheManager.getCache("passwordRetryCache");
        }
    
    
        @Override
        public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
            String username = (String)token.getPrincipal();
            //retry count + 1
            AtomicInteger retryCount = passwordRetryCache.get(username);
            if(retryCount == null) {
                retryCount = new AtomicInteger(0);
                passwordRetryCache.put(username, retryCount);
            }
            if(retryCount.incrementAndGet() > 8) {
                //if retry count > 5 throw
                throw new ExcessiveAttemptsException();
            }
    
            boolean matches = super.doCredentialsMatch(token, info);
            if(matches) {
                //clear retry count
                passwordRetryCache.remove(username);
            }
            return matches;
        }
    }
    ···
    
    - 回头看assertCredentialsMatch函数,校验失败后,抛出IncorrectCredentialsException异常,然后AuthenticatingSecurityManager的login抛该异常,登录失败
    
    到此,shiro的验证过程结束,其他的一些细节,有兴趣的可以去研究源码。

    相关文章

      网友评论

          本文标题:Shiro工作过程分析

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