本文以循序渐进的方式解析Shiro整个login过程的处理,读者可以边阅读本文边自己看代码来思考体会,如有问题,欢迎评论区探讨!
笔者shiro的demo源码路径:https://github.com/roostinghawk/ShiroDemo.git
1. 入口:Suject.login (比如Spring一般为LoginController)
@PostMapping("/login") public String login(@RequestParam("loginName") String loginName, @RequestParam("password") String password, Model model){ UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginName, password); Subject subject = SecurityUtils.getSubject(); try { subject.login(usernamePasswordToken); // 入口 }catch (IncorrectCredentialsException ice){ model.addAttribute("login","password error"); return "error"; }catch (UnknownAccountException uae) { model.addAttribute("login","userName error"); return "error"; }return "redirect:/index"; }
2. 接口Subject实现类DelegatingSubject的login方法
public void login(AuthenticationToken token) throws AuthenticationException { clearRunAsIdentitiesInternal(); Subject subject = securityManager.login(this, token); // 此处调用SecurityManager登录,从此入口向下解析 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; } }
3. 接口SecurityManager实现类DefaultSecurityManager的login方法
/** * First authenticates the {@code AuthenticationToken} argument, and if successful, constructs a * {@code Subject} instance representing the authenticated account's identity. * <p/> * Once constructed, the {@code Subject} instance is then {@link #bind bound} to the application for * subsequent access before being returned to the caller. * * @param token the authenticationToken to process for the login attempt. * @return a Subject representing the authenticated user. * @throws AuthenticationException if there is a problem authenticating the specified {@code token}. */ public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException { AuthenticationInfo info; try { info = authenticate(token); // 验证凭证: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); // 创建Subject:createSubject(涉及到Session的创建,不在此文解析) onSuccessfulLogin(token, info, loggedIn); // rememberMe处理 return loggedIn; }
对于1)的代码,继续向下分析,是使用Authenticator的委托来实现
/** * Delegates to the wrapped {@link org.apache.shiro.authc.Authenticator Authenticator} for authentication. */ public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException { return this.authenticator.authenticate(token); }
实际调用的是抽象类AbstractAuthenticator的authenticate的方法
public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException { if (token == null) { throw new IllegalArgumentException("Method argument (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); if (log.isWarnEnabled()) log.warn(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的实现,实际在子类ModularRealmAuthenticator
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException { assertRealmsConfigured(); Collection<Realm> realms = getRealms(); // 看到这里,大家应该明白realm的查找和执行时机了吧(在config中设置SecurityManager的realm)
if (realms.size() == 1) { return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken); } else { return doMultiRealmAuthentication(realms, authenticationToken); } }
在demo中,我们使用的单一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); } AuthenticationInfo info = realm.getAuthenticationInfo(token); // 此处调用的还不是自定义的realm的方法,而是其父类AuthenticatingRealm 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的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); // 此时才会真正的执行自定义的realm 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); // 真正的密码校验是在realm执行完成之后的 } else { log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token); } return info; }
大家这时候可能有一个疑问,为什么父类的protected方法会跑到子类执行呢?
这是因为执行的realm实例本身就是自定义的MyRealm,对于子类未实现而在抽象父类中实现的方法,当然是执行父类的方法,而对于已经覆盖的方法,当然也会走到子类的实现,这就是抽象和继承的好处!
接下来看自定义的realm
/** * 提供帐户信息,返回认证信息 (其实realm并不负责校验密码,而是负责把用户信息从数据源中取出来) * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { String loginName = (String)authenticationToken.getPrincipal(); User user = userService.findUserByLoginName(loginName); if(user == null) { //用户不存在就抛出异常 throw new UnknownAccountException(); } //密码可以通过SimpleHash加密,然后保存进数据库。 //此处是获取数据库内的账号、密码、盐值,保存到登陆信息info中 return new SimpleAuthenticationInfo( loginName, user.getPassword(), ByteSource.Util.bytes(Hex.decode(user.getSalt())), getName()); }
4. 自定义realm执行完后,会返回到AuthenticatingRealm的getAuthenticationInfo进行密码校验assertCredentialsMatch (当然前提是取到了该用户)
5. 一步步回溯到DefaultSecurityManager的login方法中进行登录成功后的处理:session保存和rememberMe处理
(在config中设置SecurityManager的realm属性设置)