CAS 集成 JPA(关系数据库)存储 YubiKey 设备注册信息:YubiKey-Authentication-Registration-JPA 实战指南
CAS 集成 JPA(关系数据库)存储 YubiKey 设备注册信息:YubiKey-Authentication-Registration-JPA 实战指南
YubiKey 是 Yubico 推出的硬件双因子认证令牌,其一次性密码(OTP)可通过云端服务完成校验。当 Apereo CAS 以 YubiKey 作为多因子认证(MFA)手段时,需要为每个用户保存"哪个 YubiKey 设备被允许登录"的注册记录,而本文要介绍的 JPA 注册存储方案,正是把这些设备注册记录持久化到 MySQL、PostgreSQL、SQL Server 等关系数据库中。读完本文,你将掌握:如何启用 cas-server-support-yubikey-jpa 模块、如何配置 cas.authn.mfa.yubikey.jpa.* 系列参数、JPA 注册表的自动建表结构与各字段含义,以及 CAS 底层如何通过 JpaYubiKeyAccountRegistry 完成设备记录的增删改查。
一、模块引入:在 WAR Overlay 中添加依赖
JPA 注册方案是 CAS 为 YubiKey 设备注册提供的存储后端之一(完整的后端清单可参考 YubiKey-Authentication.md,包括 JSON、REST、Permissive、JPA、Redis、DynamoDb、MongoDb 与自定义实现)。启用方式与 CAS 其他模块一致,在 WAR overlay 的构建文件中加入如下依赖:
implementation "org.apereo.cas:cas-server-support-yubikey-jpa"
从配置模型源码看,该模块对应 YubiKeyJpaMultifactorProperties,其类上标注了 @RequiresModule(name = "cas-server-support-yubikey-jpa"),即该配置段只有在引入上述依赖后才生效,否则相关属性会被 CAS 忽略(见 YubiKeyJpaMultifactorProperties.java)。
同时,YubiKey 认证的基础模块 cas-server-support-yubikey 也必须存在,因为它提供 client-id、secret-key、设备校验逻辑与 webflow 等公共能力;YubiKeyJpaMultifactorProperties 正是作为 cas.authn.mfa.yubikey.jpa 嵌套属性挂在 YubiKeyMultifactorAuthenticationProperties 之下的(见 YubiKeyMultifactorAuthenticationProperties.java)。
二、配置前缀:cas.authn.mfa.yubikey.jpa
引入模块后,所有 JPA 相关配置均位于前缀:
cas.authn.mfa.yubikey.jpa
该配置段继承自 CAS 通用的 AbstractJpaProperties(所有 JPA 持久化配置共享的基类,见 AbstractJpaProperties.java),因此它拥有完整的关系数据库连接参数。常用配置项如下:
| 配置键 | 默认值 | 说明 |
|---|---|---|
cas.authn.mfa.yubikey.jpa.dialect |
org.hibernate.dialect.HSQLDialect |
Hibernate 方言,用于把通用 SQL 翻译成特定数据库的 DDL/DML。生产环境必须按实际数据库改为对应方言 |
cas.authn.mfa.yubikey.jpa.ddl-auto |
update |
Hibernate 自动建表/更新表结构策略。可选 validate(仅校验不改库)、update(更新表结构)、create(建表并销毁旧数据)、create-drop(会话结束即删表)、none(不做任何事)。生产环境建议 validate 或 none,测试环境常用 create-drop |
cas.authn.mfa.yubikey.jpa.driver-class |
org.hsqldb.jdbcDriver |
JDBC 驱动类名,必须与所选数据库匹配 |
cas.authn.mfa.yubikey.jpa.url |
jdbc:hsqldb:mem:cas-hsql-database |
数据库连接 URL,支持 SpEL 表达式 |
cas.authn.mfa.yubikey.jpa.user |
sa |
数据库用户名,需具备执行 schema 变更的权限 |
cas.authn.mfa.yubikey.jpa.password |
空 | 数据库连接密码 |
cas.authn.mfa.yubikey.jpa.default-catalog / default-schema |
空 | 限定生成 SQL 中的表 catalog / schema |
cas.authn.mfa.yubikey.jpa.health-query |
空 | 连接健康检查 SQL(用于不支持 JDBC4 Connection.isValid() 的旧数据库) |
cas.authn.mfa.yubikey.jpa.idle-timeout |
PT10M |
连接池中连接允许空闲的最大时长 |
cas.authn.mfa.yubikey.jpa.connection-timeout |
PT30S |
获取连接的最大等待毫秒数 |
cas.authn.mfa.yubikey.jpa.data-source-name |
空 | 若指定,则通过 JNDI 查找该数据源 |
cas.authn.mfa.yubikey.jpa.pool.* |
— | 数据库连接池(HikariCP)相关参数 |
cas.authn.mfa.yubikey.jpa.batch-size / fetch-size |
100 |
Hibernate 批量更新大小 / 查询抓取行数 |
cas.authn.mfa.yubikey.jpa.properties |
空 Map | 以键值对形式追加给 Hibernate(或连接提供方)的额外设置 |
cas.authn.mfa.yubikey.jpa.physical-naming-strategy-class-name |
org.apereo.cas.hibernate.CasHibernatePhysicalNamingStrategy |
Hibernate 物理命名策略类全限定名 |
cas.authn.mfa.yubikey.jpa.isolation-level-name |
ISOLATION_READ_COMMITTED |
事务隔离级别 |
cas.authn.mfa.yubikey.jpa.propagation-behavior-name |
PROPAGATION_REQUIRED |
事务传播行为 |
2.1 生产示例(MySQL)
cas.authn.mfa.yubikey.jpa.ddl-auto=update
cas.authn.mfa.yubikey.jpa.user=casuser
cas.authn.mfa.yubikey.jpa.password=changeit
cas.authn.mfa.yubikey.jpa.driver-class=com.mysql.cj.jdbc.Driver
cas.authn.mfa.yubikey.jpa.url=jdbc:mysql://localhost:3306/cas?allowPublicKeyRetrieval=true&characterEncoding=UTF-8&useSSL=FALSE
cas.authn.mfa.yubikey.jpa.dialect=org.hibernate.dialect.MySQLDialect
2.2 生产示例(PostgreSQL)
cas.authn.mfa.yubikey.jpa.ddl-auto=update
cas.authn.mfa.yubikey.jpa.user=postgres
cas.authn.mfa.yubikey.jpa.password=changeit
cas.authn.mfa.yubikey.jpa.driver-class=org.postgresql.Driver
cas.authn.mfa.yubikey.jpa.url=jdbc:postgresql://localhost:5432/yubikey
cas.authn.mfa.yubikey.jpa.dialect=org.hibernate.dialect.PostgreSQLDialect
2.3 生产示例(Microsoft SQL Server)
cas.authn.mfa.yubikey.jpa.ddl-auto=update
cas.authn.mfa.yubikey.jpa.user=sa
cas.authn.mfa.yubikey.jpa.password=p@ssw0rd
cas.authn.mfa.yubikey.jpa.driver-class=com.microsoft.sqlserver.jdbc.SQLServerDriver
cas.authn.mfa.yubikey.jpa.url=jdbc:sqlserver://localhost:1433;databaseName=yubikey;useUnicode=true;characterEncoding=UTF-8;encrypt=false;trustServerCertificate=true
cas.authn.mfa.yubikey.jpa.dialect=org.hibernate.dialect.SQLServerDialect
上述三个示例与仓库中针对 MySQL、PostgreSQL、SQL Server 的集成测试配置完全一致(见 MySQLJpaYubiKeyAccountRegistryTests.java、PostgresJpaYubiKeyAccountRegistryTests.java 与 MicrosoftSQLServerJpaYubiKeyAccountRegistryTests.java),可直接作为接线参考。
另外还需注意:CAS 的 JPA 能力普遍依赖 JDBC 驱动模块 cas-server-support-jdbc-drivers(AbstractJpaProperties 上标注了 @RequiresModule(name = "cas-server-support-jdbc-drivers")),请确保 overlay 中一并包含相应驱动依赖。
三、自动建表:YubiKeyAccount 表结构
启用模块后,CAS 会自动创建并维护数据库 schema。整个注册模型围绕一张主表 YubiKeyAccount 展开(文档给出的字段如下):
| Field | Description |
|---|---|
id |
Unique record identifier, acting as the primary key.(唯一记录标识,作为主键) |
publicId |
The public identifier/key of the device used for authentication.(用于认证的设备公钥/公共标识) |
username |
The username whose device is registered.(注册了设备的用户名) |
3.1 源码视角:实体与字段的真实构成
结合源码可以更精确地还原这张表的真实结构。核心实体是 JpaYubiKeyAccount(见 JpaYubiKeyAccount.java),它标注了 @Entity 与 @Table(name = "YubiKeyAccount"),并继承自 YubiKeyAccount(见 YubiKeyAccount.java):
id:主键,@Id+@GeneratedValue(strategy = GenerationType.AUTO),由数据库自增生成;username:@Column(nullable = false),即"谁注册了这个设备",在YubiKeyAccount上同时标注了@JsonProperty,序列化时也会输出;tenant:@Column,可空,用于多租户场景下的租户标识;devices:一个@ElementCollection(fetch = FetchType.EAGER)的设备集合,映射到独立的YubiKeyRegisteredDevice表(@CollectionTable(name = "YubiKeyRegisteredDevice"))。
而设备条目本身是一个 @Embeddable 实体 YubiKeyRegisteredDevice(见 YubiKeyRegisteredDevice.java),其字段包括:
id:设备在用户账户内的唯一编号;publicId:@Column(nullable = false, length = 2048),即文档表格中的publicId——YubiKey 设备用于认证的公共标识;name:@Column(nullable = false),设备名称;tenant:可空的租户字段;registrationDate:注册时间,默认取 UTC 当前时间。
也就是说,文档表格中列出的 publicId 实际落在子表 YubiKeyRegisteredDevice 中,而 YubiKeyAccount 主表自身还包含 tenant 字段,并通过一对多元素集合与设备表关联。了解这一层结构,对排查"为什么我的表里多了几列/为什么多了一张表"这类问题很有帮助。
四、底层实现:JpaYubiKeyAccountRegistry 的工作方式
JPA 存储后端的核心类是 JpaYubiKeyAccountRegistry(见 JpaYubiKeyAccountRegistry.java),它继承自 BaseYubiKeyAccountRegistry,通过 JPA EntityManager 直接操作实体。关键实现点如下:
- 按用户名查询:
getAccountInternal(uid)执行SELECT r from JpaYubiKeyAccount r WHERE r.username = :username这类 JPQL,命中后先detach再返回,避免后续修改污染持久化上下文;查不到时捕获NoResultException返回null; - 保存/更新:
save(...)把注册请求(用户名 + 设备列表 + 租户)组装成JpaYubiKeyAccount后执行entityManager.merge(...);update(...)同样通过merge是否返回非空判断是否成功; - 删除:
delete(uid)先查询再entityManager.remove;delete(username, deviceId)则从账户的devices集合中移除指定设备后merge回写;deleteAll()遍历全部记录逐一移除; - 事务管理:类上标注
@Transactional(transactionManager = "transactionManagerYubiKey"),使用 CAS 为该模块单独注册的事务管理器。
JpaYubiKeyAccountRegistry 并非普通 Bean 的简单注入,而是由自动配置类 CasJpaYubiKeyAutoConfiguration(见 CasJpaYubiKeyAutoConfiguration.java)组装:
- 条件装配:整个自动配置类标注了
@ConditionalOnFeatureEnabled(feature = YubiKey, module = "jpa"),只有 JPA 模块被启用时才生效; - EntityManagerFactory:通过
JpaBeanFactory构建,持久化单元名为jpaYubiKeyRegistryContext,扫描包指向JpaYubiKeyAccount所在包(即 JpaYubiKeyAccount.java 的包),数据源来自dataSourceYubiKey; - 事务管理器:注册
transactionManagerYubiKey(JpaTransactionManager),与JpaYubiKeyAccountRegistry上的@Transactional注解配对; - 数据源:
dataSourceYubiKey由JpaBeans.newDataSource(casProperties.getAuthn().getMfa().getYubikey().getJpa())创建,即直接读取本文第二节的配置段,默认以 HSQLDB 内存库起步; - 注册表装配:
yubiKeyAccountRegistryBean 将YubiKeyAccountValidator注入JpaYubiKeyAccountRegistry,同时通过yubikeyAccountCipherExecutor(加密执行器)对注册记录做加解密处理——这对应YubiKeyMultifactorAuthenticationProperties.crypto配置段(见 YubiKeyMultifactorAuthenticationProperties.java),负责对 YubiKey 注册记录的签名与加密。
五、设备校验与认证流程中的角色
值得强调的是,JPA 存储只是"注册记录的存放地",YubiKey 认证的完整流程仍然遵循 YubiKey-Authentication.md 描述的主线:
- 用户提交 YubiKey OTP;
- CAS 通过
client-id/secret-key调用 Yubico 云 API 校验 OTP 有效性(默认校验策略为VERIFY,也可配置为SKIP或REJECT,见 YubiKeyMultifactorAuthenticationProperties.java 中的YubiKeyDeviceValidationOptions枚举); - 设备校验通过后,CAS 在配置的注册后端中查找与"当前用户 + 设备
publicId"匹配的记录,只有已注册的设备才被允许完成 MFA。
因此,在采用 JPA 注册方案时,设备必须先通过 out-of-band(带外)注册流程写入 YubiKeyAccount 表,之后认证才会成功;未注册的设备即便 OTP 有效也会被拒绝。若需要"放行所有设备"或"拒绝所有设备",可分别使用 Permissive(见 YubiKey-Authentication-Registration-Permissive.md)或 REJECT 校验策略。
六、测试验证:仓库如何保证 JPA 注册可用性
仓库为 JPA 注册方案提供了完善的测试支撑,可作为接线与排错的直接参照:
- 单元/集成测试基类 JpaYubiKeyAccountRegistryTests.java 使用 HSQLDB 内存库(
jdbc:hsqldb:mem:yubikey)与ddl-auto=create-drop,覆盖了注册表的基础增删改查与设备管理行为; - 多数据库矩阵测试:MySQL、PostgreSQL、SQL Server 三套测试(分别监听 3306/5432/1433 端口)直接验证了不同方言、驱动与 URL 下的建表与读写兼容性,测试中使用的完整属性集就是第二节示例的出处;
- 上层行为测试:YubiKeyAuthenticationHandlerTests.java 等测试进一步验证了认证处理器与注册表的交互。
七、小结与排错提示
把 YubiKey 设备注册记录放进关系数据库,只需三步:在 WAR overlay 加入 cas-server-support-yubikey-jpa 依赖、按数据库类型配置 cas.authn.mfa.yubikey.jpa.*、确认表 YubiKeyAccount 已由 Hibernate 自动创建。排错时可重点关注:
- 表结构异常:核对
ddl-auto策略与dialect是否与真实数据库匹配;schema 变更时不要在生产使用create-drop(会丢失全部注册数据); - 驱动缺失:检查
cas-server-support-jdbc-drivers是否在依赖中; - 多数据源混淆:YubiKey 使用独立数据源
dataSourceYubiKey与事务管理器transactionManagerYubiKey,与 CAS 其他 JPA 存储(如 ticket registry、audit)彼此隔离,互不影响; - 记录未生效:确认设备的
publicId与username已正确写入,且注册记录经过了yubikeyAccountCipherExecutor的加解密(涉及cas.authn.mfa.yubikey.crypto.*配置)。
掌握了以上内容,你就拥有了"YubiKey 设备注册持久化到关系数据库"这一完整闭环的部署与排错能力。