如果 Realm 返回了空 AuthenticationInfo,Shiro 会怎样处理?

解读

在国内互联网或金融级面试中,这道题常被用来**“过滤只会背 API 的候选人”**。面试官真正想确认的是:

  1. 你是否读过 Shiro 的核心认证链路源码(AuthenticatingRealm#doGetAuthenticationInfo → ModularRealmAuthenticator#doSingleRealmAuthentication);
  2. 能否把“空 AuthenticationInfo”与“用户不存在”“密码错误”两种业务语义区分开;
  3. 是否具备**“防御性编程”**意识,能指出空指针、日志缺失、暴力枚举等线上隐患。

一句话:空 AuthenticationInfo 不是“认证失败”,而是“账号在系统中不存在”的信号,Shiro 会把它立刻包装成 UnknownAccountException 并终止后续 Realm 链。

知识点

  1. 认证主流程:Subject.login() → SecurityManager.login() → Authenticator.authenticate() → Realm.getAuthenticationInfo()。
  2. 关键判空位置:
    ModularRealmAuthenticator.doSingleRealmAuthentication(Realm realm, AuthenticationToken token)
    源码行:AuthenticationInfo info = realm.getAuthenticationInfo(token);
    紧跟着:if (info == null) throw new UnknownAccountException(...)。
  3. 异常语义:
    • UnknownAccountException:账号在 Realm 中查不到,禁止继续重试;
    • IncorrectCredentialsException:账号存在但密码/凭证错;
    • AuthenticationException:以上两者的父类,统一捕获。
  4. 多 Realm 策略:
    • FirstSuccessfulStrategy 遇到空 info 会继续遍历下一个 Realm;
    • AtLeastOneSuccessfulStrategy 与 AllSuccessfulStrategy 会把空 info 当成失败计数;
      但最终只要没有任何 Realm 返回非空 info,同样抛 UnknownAccountException。
  5. 国内合规注意:
    • 登录接口不能区分“账号不存在”和“密码错误”返回给前端,需统一模糊提示;
    • 日志侧必须明细记录异常类型,方便审计与溯源,满足《网络安全法》日志留存要求。

答案

当某个 Realm 的 doGetAuthenticationInfo 返回 null 时,Shiro 的 ModularRealmAuthenticator 会立即抛出 UnknownAccountException,不再调用任何后续 Realm,也不会进行密码匹配。
因此:

  • 认证失败,Subject.login() 终止;
  • 不会触发 CredentialsMatcher,杜绝了 Timing Attack;
  • 上层业务只需捕获 AuthenticationException,即可感知“账号不存在”场景。

拓展思考

  1. 线上踩坑案例:
    某电商把“手机号未注册”直接提示给用户,被黑产利用手机号遍历撞库。修复方案:
    • Realm 里返回 new SimpleAuthenticationInfo("", "", getName()) 伪装非空,主动进入密码比对流程,让外部无法通过异常类型区分账号是否存在;
    • 登录接口统一返回“用户名或密码错误”,日志内部再记录 UnknownAccountException 与 IncorrectCredentialsException 的区分。
  2. 性能调优:
    读多写少的用户表,给手机号/邮箱加唯一索引,并把查询结果缓存到Caffeine 本地缓存(5 min TTL),避免每次登录都打到 MySQL。
  3. 多租户场景:
    在 SaaS 平台中,租户隔离字段(tenant_id)必须作为联合查询条件;否则 A 租户输入 B 租户存在的用户名,会被误判为“账号不存在”,从而泄露用户名。
  4. 面试加分回答:
    “如果让我设计,我会继承 AuthenticatingRealm 并重写 assertCredentialsMatch,在账号不存在时仍执行一次假的哈希计算(BCrypt.checkpw("dummy", "$2a$10$...")),让接口耗时恒定,进一步抵御时间侧信道攻击。”