如何为 RPA 签发长期有效的 API Key 并限制 IP?
解读
面试官把场景限定在“RPA(机器人流程自动化)”这一国内政务、金融高频落地的方向,核心诉求有两点:
- 长期有效:RPA 7×24 无人值守,不能因 Token 过期导致流程中断;
- IP 白名单:RPA 通常部署在固定 ECS、私有云或政务网段,必须防止 Key 泄露后被二次分发。
Shiro 原生只提供 UsernamePasswordToken、JwtToken 等通用实现,没有“API Key + IP 绑定”这一领域模型,因此需要二次扩展。面试官想观察候选人能否:
- 在不破坏 Shiro 三级架构(Subject→SecurityManager→Realm)的前提下,自定义 AuthenticationToken 与 CredentialsMatcher;
- 利用 Shiro 的 IniSecurityManagerFactory / Spring Boot Starter 两种配置方式,把“长期有效”与“IP 限制”做成可热更新的规则;
- 兼顾国内等保 2.0 对“密钥存储安全”“日志留痕”的合规要求。
知识点
- AuthenticationToken 扩展:实现 HostAuthenticationToken 接口,新增 apiKey、clientIp 两个字段,确保后续 Realm 能拿到原始 IP。
- CredentialsMatcher 扩展:重写 doCredentialsMatch,在比对 Key 之后,再校验当前请求 IP 是否在白名单;白名单支持 CIDR,方便政务网段 10.0.0.0/8、172.16.0.0/12 批量配置。
- Realm 设计:
- 采用 AuthorizingRealm 而非 AuthenticatingRealm,后续可直接复用 doGetAuthorizationInfo 做细粒度授权;
- 缓存使用 Shiro 内置 EhCache,TTL 设为 -1 实现“长期有效”,但提供“手动失效”接口,满足运营侧紧急吊销需求。
- Key 生成策略:国内金融场景普遍要求 国密 SM4 对称加密 + 外部 KMS;Key 明文只在内存中出现,落库保存 SM4 密文,满足等保“密钥不落地”。
- IP 获取方式:
- 传统单体:ServletRequest.getRemoteAddr() 即可;
- 微服务 + 网关:必须取 X-Forwarded-For 第一个非内网 IP,并配合 nginx real-ip 模块,防止伪造。
- 热更新:
- 非 Spring 环境:把白名单写在 shiro-apikey.ini,通过 IniSecurityManagerFactory.reload() 完成秒级刷新;
- Spring Boot:使用 @ConfigurationProperties + @RefreshScope,结合 Nacos、Apollo 实现动态推送,无需重启 JVM。
- 审计日志:
- 实现 AuthenticationListener 的 onSuccess/onFailure,把“时间戳、API Key 前 6 位、IP、结果”异步写入 Log4j2 Kafka Appender,供 ELK 后续溯源。
答案
步骤一:定义 HostAuthenticationToken
public class ApiKeyHostToken implements HostAuthenticationToken {
private final String apiKey;
private final String clientIp;
// 省略构造、getter
@Override public Object getPrincipal() { return apiKey; }
@Override public Object getCredentials() { return apiKey; }
@Override public String getHost() { return clientIp; }
}
步骤二:自定义 Realm
public class ApiKeyRealm extends AuthorizingRealm {
@Autowired private ApiKeyService apiKeyService; // 操作数据库或缓存
@Autowired private IpWhitelistService ipService; // 判断 IP 白名单
public ApiKeyRealm() {
// 长期有效,缓存永不过期
setAuthenticationCachingEnabled(true);
setAuthorizationCachingEnabled(true);
setCacheManager(new EhCacheManager());
}
@Override public boolean supports(AuthenticationToken token) {
return token instanceof ApiKeyHostToken;
}
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
ApiKeyHostToken t = (ApiKeyHostToken) token;
String apiKey = t.getApiKey();
String ip = t.getHost();
// 1. 校验 Key 是否存在
ApiKeyEntity entity = apiKeyService.findByKey(apiKey);
if (entity == null) throw new UnknownAccountException("invalid apiKey");
// 2. 校验 IP 白名单
if (!ipService.inWhitelist(ip, entity.getCidrList()))
throw new DisabledAccountException("ip not in whitelist");
// 3. 返回带盐值的 SimpleAuthenticationInfo,后续可扩展为国密 SM4
return new SimpleAuthenticationInfo(
entity.getRobotId(), // principal
entity.getSecret(), // credentials
ByteSource.Util.bytes(entity.getSalt()),
getName());
}
// 如需授权,可继续实现 doGetAuthorizationInfo
}
步骤三:自定义 CredentialsMatcher 完成“双重校验”
public class ApiKeyCredentialsMatcher extends CredentialsMatcherAdapter {
@Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
// 第一关:Key 字符串相等
String incoming = (String) token.getCredentials();
String stored = (String) info.getCredentials();
return incoming != null && incoming.equals(stored);
// IP 已在 Realm 提前校验,此处无需重复
}
}
步骤四:Spring Boot 装配
@Configuration
public class ShiroConfig {
@Bean
public ApiKeyRealm apiKeyRealm() {
ApiKeyRealm realm = new ApiKeyRealm();
realm.setCredentialsMatcher(new ApiKeyCredentialsMatcher());
return realm;
}
@Bean
public DefaultWebSecurityManager securityManager(ApiKeyRealm realm) {
DefaultWebSecurityManager sm = new DefaultWebSecurityManager(realm);
// 关闭 Session,纯 Stateless
DefaultSessionManager sessionManager = new DefaultSessionManager();
sessionManager.setSessionValidationSchedulerEnabled(false);
sm.setSessionManager(sessionManager);
return sm;
}
@Bean
public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager sm) {
ShiroFilterFactoryBean fb = new ShiroFilterFactoryBean();
fb.setSecurityManager(sm);
Map<String, String> map = new LinkedHashMap<>();
map.put("/rpa/**", "anon"); // 自定义过滤器接管
fb.setFilterChainDefinitionMap(map);
Map<String, Filter> filters = new HashMap<>();
filters.put("anon", new ApiKeyAuthenticationFilter()); // 见步骤五
fb.setFilters(filters);
return fb;
}
}
步骤五:ApiKeyAuthenticationFilter 负责把请求包装成 Token
public class ApiKeyAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse resp,
FilterChain chain)
throws ServletException, IOException {
String key = req.getHeader("X-API-KEY");
if (key == null || key.isEmpty()) {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "missing apiKey");
return;
}
String ip = getClientIp(req); // 取 X-Forwarded-For 第一个公网 IP
ApiKeyHostToken token = new ApiKeyHostToken(key, ip);
try {
Subject subject = SecurityUtils.getSubject();
subject.login(token); // 走上面 Realm
chain.doFilter(req, resp);
} catch (AuthenticationException e) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
}
}
private String getClientIp(HttpServletRequest req) {
String xf = req.getHeader("X-Forwarded-For");
if (xf != null && !xf.isEmpty()) {
return xf.split(",")[0].trim();
}
return req.getRemoteAddr();
}
}
步骤六:签发与吊销
- 签发:管理后台调用 ApiKeyService.issue(robotId, cidrList),内部使用 SecureRandom 生成 32 位 URL-Safe Key,SM4 加密后落库,同时把明文 Key 一次性返回给 RPA,后台不保存明文,满足等保要求。
- 吊销:提供 /admin/revoke 接口,删除缓存 + 数据库记录,EhCache 的 removeCache(name) 可立即生效;若使用 RedisCache,则发送 del 指令即可。
通过以上六步,即可在 Shiro 中完成“长期有效 + IP 白名单”的 API Key 机制,全程不侵入 Shiro 核心,保持高内聚、低耦合,并满足国内等保、国密、热更新、审计四大硬性指标。
拓展思考
- 多租户场景:如果 RPA 平台服务多家银行,可把 tenantId 加入 ApiKeyHostToken,Realm 查询时增加租户维度,避免 Key 跨租户越权。
- 密钥轮换:虽然业务要求“长期有效”,但等保 2.0 建议“最长一年更换”。可引入 双 Key 机制:新 Key 生成后,旧 Key 保留 24 h 宽限期,通过 Key-Version 头实现平滑切换,RPA 无需停机。
- 性能压测:政务云环境 QPS 往往不高,但金融行情 RPA 可能瞬时 5 k QPS。此时可把 IP 白名单 预编译成 IPv4IntRange,再用 BitSet 判断,O(1) 复杂度;同时把 Realm 的 doGetAuthenticationInfo 结果缓存到 Caffeine,比 EhCache 减少 30% 延迟。
- 零信任演进:未来若接入 Service Mesh + mTLS,可把 API Key 作为 Authorization Policy 的 RequestPrincipal,Sidecar 统一校验,业务代码无需再关心 Shiro,实现安全与业务彻底解耦。