shrio登录流程

 

 

1、登录发起

shrio登录是由subject.login(token)发起的通过SecurityUtils.getSubject()获取subject,subject是绑定线程的,在web环境中通过FormAuthenticationFilter 中onAccessDenied(……)-> executeLogin(request, response)->Subject subject = getSubject(request, response);subject.login(token);进行subject.login(token)的调用

 

1.1  SecurityUtils中创建subject的方法

public static Subject getSubject() {
    Subject subject = ThreadContext.getSubject();
    if (subject == null) {
        subject = (new Subject.Builder()).buildSubject();
        ThreadContext.bind(subject);
    }
    return subject;
}

其中 subject = (new Subject.Builder()).buildSubject();调用的是securityManager.createSubject(this.subjectContext);securityManager看你自己在环境中的绑定。

DefaultWebSecurityManager类中createSubject(subjectContext) 的具体实现在DefaultSecurityManager类中

public Subject createSubject(SubjectContext subjectContext) {
    //create a copy so we don't modify the argument's backing map:
    SubjectContext context = copy(subjectContext);

    //ensure that the context has a SecurityManager instance, and if not, add one:
    context = ensureSecurityManager(context);

    //Resolve an associated Session (usually based on a referenced session ID), and place it in the context before
    //sending to the SubjectFactory.  The SubjectFactory should not need to know how to acquire sessions as the
    //process is often environment specific - better to shield the SF from these details:
    context = resolveSession(context);//其中调用了getSession(SessionKey key)

    //Similarly, the SubjectFactory should not require any concept of RememberMe - translate that here first
    //if possible before handing off to the SubjectFactory:
    context = resolvePrincipals(context);

    Subject subject = doCreateSubject(context);

    //save this subject for future reference if necessary:
    //(this is needed here in case rememberMe principals were resolved and they need to be stored in the
    //session, so we don't constantly rehydrate the rememberMe PrincipalCollection on every operation).
    //Added in 1.2:
    save(subject);

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

web环境中我们使用的是DefaultWebSecurityManager,DefaultWebSecurityManager的构造方法如下
public DefaultWebSecurityManager() {
    super();
    ((DefaultSubjectDAO) this.subjectDAO).setSessionStorageEvaluator(new DefaultWebSessionStorageEvaluator());
    this.sessionMode = HTTP_SESSION_MODE;
    setSubjectFactory(new DefaultWebSubjectFactory());
    setRememberMeManager(new CookieRememberMeManager());
    setSessionManager(new ServletContainerSessionManager());
}

在其中我们可以找到 setSubjectFactory(new DefaultWebSubjectFactory()),即在DefaultWebSecurityManager中shrio使用的是DefaultWebSubjectFactory工厂类。

 DefaultWebSubjectFactory类中的createSubject方法如下

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

所以使用DefaultWebSecurityManager我们最终创建的是WebDelegatingSubject

 

1.2 Session的创建

DefaultSecurityManager中的createSubject(subjectContext) 方法中调用了resolveSession(context),

resolveSession(context)和Session的创建有关,DefaultSecurityManager继承了SessionsSecurityManager。

在SessionsSecurityManager中 getSession(SessionKey key)创建了Session,resolveSession(context)中调用了getSession(SessionKey key)。

SessionsSecurityManager中的getSession(SessionKey key)方法如下

public Session getSession(SessionKey key) throws SessionException {
    return this.sessionManager.getSession(key);
}
SessionsSecurityManager中的DefaultSessionManager包含了
this.sessionFactory = new SimpleSessionFactory();
this.sessionDAO = new MemorySessionDAO();

sessionFactory 可控制session的创建,sessionDAO中定义了session的生命周期监听事件

2、登录

2.1 登录通道:

securityManager->authenticator->realm

WebDelegatingSubject类继承了DelegatingSubject,在DelegatingSubject中我们可以找到subject.login(token),具体如下
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;
    }
}

可以看到 subject.login(token) 中调用了securityManager.login(this, token);

在此之前我们先看一下DefaultWebSecurityManager的继承关系

 

在web环境中我们找到的DefaultWebSecurityManager的login(Subject subject, AuthenticationToken token)(在DefaultSecurityManager类中,DefaultWebSecurityManager继承了DefaultSecurityManager)

 

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);//根据设置创建cookie

    return loggedIn;
}
 我们先看info = authenticate(token),authenticate(token)的具体实现在AuthenticatingSecurityManager类中,如下:
public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
    return this.authenticator.authenticate(token);
}

在AuthenticatingSecurityManager类中的构造函数中我们不难发现

this.authenticator = new ModularRealmAuthenticator();

所以具体的登录认证就在ModularRealmAuthenticator中了

2.2 ModularRealmAuthenticator的authenticate(token)

ModularRealmAuthenticator继承了AbstractAuthenticator,authenticate(token)的具体实现在AbstractAuthenticator中,如下:
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;
}

他首先进行的是doAuthenticate(token); 然后notifySuccess(token, info);ModularRealmAuthenticator覆盖了AbstractAuthenticator的doAuthenticate(token);ModularRealmAuthenticator中的Authenticate(token)如下:

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

在ModularRealmAuthenticator初始化了AtLeastOneSuccessfulStrategy验证策略,用户可自己验证策略定义。

ModularRealmAuthenticator的realms 来自哪里呢?我们只在SecurityManager中设置了realm,在

RealmSecurityManager中我们有 setRealm(Realm realm) ,它调用了setRealms(realms),setRealms又调用了afterRealmsSet()。AuthenticatingSecurityManager中我们可以找到
protected void afterRealmsSet() {
    super.afterRealmsSet();
    if (this.authorizer instanceof ModularRealmAuthorizer) {
        ((ModularRealmAuthorizer) this.authorizer).setRealms(getRealms());
    }
}

doAuthenticate完成后返回的是AuthenticationInfo

2.3 realm 验证

ModularRealmAuthenticator最终调用的是realm.getAuthenticationInfo(token),其中会进行身份的匹配;

realm中设置了credentialsMatcher,permissionResolver,permissionRoleResolver;

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值