其他分享
首页 > 其他分享> > shiro认证过程分析

shiro认证过程分析

作者:互联网

0前言

shiro身份认证过程可以从subject.login(token)开始梳理。

本节只分析基础的认证流程,认证过程的各种策略(authenticationStrategy)、以及realm的credentialsMatcher等扩展内容不是本节重点,感兴趣的童鞋可以自行分析。

首先准备了测试demo:

    @Test
    public void testCustomRealm() {

        //创建SecurityManager实例,配置realm
        org.apache.shiro.mgt.SecurityManager securityManager = new DefaultSecurityManager();
        Realm realm = new MyRealm1();
        ((DefaultSecurityManager) securityManager).setRealm(realm);

        //绑定SecurityManager给SecurityUtils
        SecurityUtils.setSecurityManager(securityManager);

        //得到Subject
        Subject subject = SecurityUtils.getSubject();

        //创建用户名/密码身份验证Token(即用户身份/凭证)
        UsernamePasswordToken token = new UsernamePasswordToken("test", "123");

        try {
            //登录,即身份验证(分析入口)
            subject.login(token);
        } catch (AuthenticationException e) {
            //身份验证失败处理
            e.printStackTrace();
        }

        //断言用户已经登录
        Assert.assertEquals(true, subject.isAuthenticated());

        //退出
        subject.logout();
    }

测试程序创建一个SecurityManager,为其配置了realm,并将SecurityManager绑定到SecurityUtils,SecurityUtils是全局唯一的,可以用来获取当前访问的的subject。然后创建了一个token,用subject模拟了一次登录,也就是调用login方法。Myrealm1定义如下:

public class MyRealm1 implements AuthenticatingRealm {

    @Override
    public String getName() {
        return "myrealm1";
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken; //仅支持UsernamePasswordToken类型的Token
    }

    @Override
    public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String username = (String)token.getPrincipal();  //得到用户名
        String password = new String((char[])token.getCredentials()); //得到密码
        if(!"test".equals(username)) {
            throw new UnknownAccountException(); //如果用户名错误
        }
        if(!"123".equals(password)) {
            throw new IncorrectCredentialsException(); //如果密码错误
        }
        //如果身份认证验证成功,返回一个AuthenticationInfo实现;
        return new SimpleAuthenticationInfo(username, password, getName());
    }
}

这里Myrealm1实现了用于认证的AuthenticatingRealm 接口,实际使用一般实现Realm的子接口AuthorizingRealm(包含认证和授权的相关方法)

 

1认证分析

subject实现类DelegatingSubject的login方法(DelegatingSubject源码254行)

    public void login(AuthenticationToken token) throws AuthenticationException {
        clearRunAsIdentitiesInternal();
        Subject subject = securityManager.login(this, token);

        //省略其他内容...
    }

DelegatingSubject调用securityManager(DefaultSecurityManager)的login来认证。

//DefaultSecurityManager源码267行
    public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
        AuthenticationInfo info;
        try {
           //调用父类AuthenticatingSecurityManager的authenticate
            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源码105行
public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
//通过认证器Authenticator认证
return this.authenticator.authenticate(token); }
//AbstractAuthenticator第188行

    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 {
            //子类ModularRealmAuthenticator实现
            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 第263行
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        assertRealmsConfigured();
        Collection<Realm> realms = getRealms();
        //按照单个realm和多个realm分别执行不同的处理逻辑
        if (realms.size() == 1) {
            return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
        } else {
            return doMultiRealmAuthentication(realms, authenticationToken);
        }
    }

接下来处理单个realm的认证情况

//ModularRealmAuthenticator 第173行
    protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
        //调用realm的实现方法supports判断是否支持的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);
        }
        //AuthenticatingRealm的getAuthenticationInfo方法
        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第563行
    public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //先看看cache里面有没有
        AuthenticationInfo info = getCachedAuthenticationInfo(token);
        if (info == null) {
            //otherwise not cached, perform the lookup:
            //这里调用自定义realm实现的方法(本文开头的MyRealm1)
            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) {
           //这个用到了CredentialsMatch功能
            assertCredentialsMatch(token, info);
        } else {
            log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}].  Returning null.", token);
        }

        return info;
    }

MyRealm1的doGetAuthenticationInfo方法会通过用户名返回提前保存的用户信息info(一般可以从数据库里读取,包括用户名、加密过的密码和salt等)。

CredentialsMatch用于将输入的token密码通过配置的加密算法和用户info中的salt进行加密后于用户的加密密码匹配。(本文的MyRealm1示例没有体现这个加密功能,直接拿密码对比,失败抛异常)

如果匹配成功会返回info信息,否则会抛出认证失败相关异常。单个realm认真流程大致已经完成,下面的多realm认证流程

//ModularRealmAuthenticator 第198行
    protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {

        AuthenticationStrategy strategy = getAuthenticationStrategy();

        AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);

        if (log.isTraceEnabled()) {
            log.trace("Iterating through {} realms for PAM authentication", realms.size());
        }

        for (Realm realm : realms) {

            aggregate = strategy.beforeAttempt(realm, token, aggregate);

            if (realm.supports(token)) {

                log.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm);

                AuthenticationInfo info = null;
                Throwable t = null;
                try {
                    info = realm.getAuthenticationInfo(token);
                } catch (Throwable throwable) {
                    t = throwable;
                    if (log.isDebugEnabled()) {
                        String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:";
                        log.debug(msg, t);
                    }
                }

                aggregate = strategy.afterAttempt(realm, token, info, aggregate, t);

            } else {
                log.debug("Realm [{}] does not support token {}.  Skipping realm.", realm, token);
            }
        }

        aggregate = strategy.afterAllAttempts(token, aggregate);

        return aggregate;
    }

多realm认证流程会在循环调用每个realm的前后加入AuthenticationStrategy 策略,shiro提供了三种策略

AtLeastOneSuccessfulStrategy:有一个realm认证成功就成功

AllSuccessfulStrategy:所有的realm认证成功才成功

FirstSuccessfulStrategy:只有第一个realm认证成功才会成功

以上三种策略不满足的话,用户可以定义实现AuthenticationStrategy 进行扩展。

 

总结一下认证流程

(1)subject.login(token) 开始认证

(2)subject会调用SecuretyManager的login(token)方法

(3)SecurityManager调用认证器Authenticator的authenticate(token)

(4)Authenticator分单realm和多realm,多realm根据不同的AuthenticationStrategy 进行认证流程

(5)最终是调用Realm的doGetAuthenticationInfo获取info信息,然后通过CredentialsMatch进行密码比较,认证失败会抛出异常

  

标签:分析,info,realm,认证,token,AuthenticationException,AuthenticationInfo,shiro
来源: https://www.cnblogs.com/ouym/p/15617188.html