用 Camel 的 undertow 组件搭建授权码流程的完整路由
解读
面试官让你“用 Camel 的 undertow 组件搭建授权码流程的完整路由”,表面看是考“怎么写一段路由”,实质是验证三件事:
- 你是否真的理解 OAuth2 授权码(authorization_code) 在浏览器、客户端、授权服务器、资源服务器之间的四次握手;
- 你是否能把“无状态 HTTP 端点 + 状态机 + 安全重定向”这些非功能性需求,用 Camel 的 undertow 组件(而非 Spring Security 等框架)自己拼装出来;
- 你是否熟悉 Camel 的 REST DSL、类型转换、Header 操作、onException、缓存与线程安全 等企业级细节。
国内面试场景里,这道题常出现在“需要自研轻量级网关 / 统一认证层”的甲方或 ISV,对方希望你证明:
- 不借助 Spring Security OAuth2 的厚重封装,也能用 Camel 快速搭出生产可用的授权中心;
- 代码量可控,单文件即可跑通,方便后续移植到 Karaf、Quarkus 或云原生环境。
知识点
- undertow 组件:Camel 对 Undertow 2.x 的轻量级封装,可在一个 JVM 内同时监听多个端口,支持 WebSocket 与 HTTP,天然适合写“零容器”的认证网关。
- 授权码流程四步曲:
a. 浏览器访问/oauth/authorize?client_id=xxx&redirect_uri=xxx&state=xxx;
b. 授权服务器返回 302 登录页;用户输入账号密码;
c. 成功后 302 到redirect_uri?code=xxx&state=xxx;
d. 客户端拿 code 换 token:POST /oauth/token。 - Camel REST DSL:用
rest().get().post()声明式写端点,比直接 from("undertow:...") 更易读,也方便后面导出 OpenAPI。 - 状态防重放:
state参数必须服务端生成并缓存,回调时校验;Camel 可用DefaultIdempotentRepository或caffeine-cache实现内存级幂等。 - 安全细节:
- 登录页表单需开启 CSRF token;
- 授权码 code 一次性,10 分钟过期;
- 客户端密钥 Basic Auth 传输,HTTPS 强制;
- 异常统一走
onException(OAuthException.class).handled(true)返回 JSON,防止堆栈泄露。
- 线程与事务:undertow 默认用 IO 线程,路由里若调本地数据库,记得用 threads().poolSize(20) 切业务线程,避免阻塞 IO。
答案
以下是一份可直接拷进 IDEA 运行的单文件示例,依赖只有 camel-spring-boot-starter + camel-undertow + camel-jackson + caffeine。它演示了“授权服务器”侧完整路由,不含业务用户库,用户库自行替换为 MyBatis 或 Redis。
@Component
public class OAuth2AuthorizationCodeRoute extends RouteBuilder {
// 内存缓存:state -> clientId
private final Cache<String, String> stateCache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).build();
// 内存缓存:code -> clientId
private final Cache<String, String> codeCache = Caffeine.newBuilder().expireAfterWrite(2, TimeUnit.MINUTES).build();
// 模拟注册客户端
private final Map<String, String> clientSecretMap = Map.of("portal", "portal-secret");
@Override
public void configure() {
onException(IllegalArgumentException.class)
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
.setBody(simple("{\"error\":\"${exception.message}\"}"));
onException(InvalidStateException.class)
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
.setBody(constant("{\"error\":\"invalid_state\"}"));
// 1. 登录页静态资源
from("undertow:http://0.0.0.0:8080/login")
.to("undertow:http://0.0.0.0:8080/login.html?matchOnUriPrefix=true");
// 2. 授权端点:/oauth/authorize
rest("/oauth")
.get("/authorize").produces("text/html")
.route()
.process(ex -> {
String clientId = ex.getIn().getHeader("client_id", String.class);
String redirectUri = ex.getIn().getHeader("redirect_uri", String.class);
String state = ex.getIn().getHeader("state", String.class);
if (!clientSecretMap.containsKey(clientId)) {
throw new IllegalArgumentException("invalid_client");
}
// 生成一次性 state
String serverState = UUID.randomUUID().toString();
stateCache.put(serverState, clientId);
ex.getIn().setHeader("serverState", serverState);
ex.getIn().setHeader("redirectUri", redirectUri);
ex.getIn().setHeader("userState", state);
})
.to("freemarker:login-form.ftl") // 返回登录页,表单里带上 serverState
.endRest()
// 3. 登录提交:/oauth/doLogin
.post("/doLogin").consumes("application/x-www-form-urlencoded")
.route()
.process(ex -> {
String username = ex.getIn().getHeader("username", String.class);
String password = ex.getIn().getHeader("password", String.class);
String serverState = ex.getIn().getHeader("serverState", String.class);
if (!"admin".equals(username) || !"admin123".equals(password)) {
throw new IllegalArgumentException("invalid_credentials");
}
String clientId = stateCache.getIfPresent(serverState);
if (clientId == null) {
throw new InvalidStateException();
}
// 生成授权码
String code = UUID.randomUUID().toString();
codeCache.put(code, clientId);
stateCache.invalidate(serverState);
// 拼回调地址
String redirectUri = ex.getIn().getHeader("redirectUri", String.class);
String userState = ex.getIn().getHeader("userState", String.class);
String location = String.format("%s?code=%s&state=%s", redirectUri, code, userState);
ex.getMessage().setHeader(Exchange.HTTP_RESPONSE_CODE, 302);
ex.getMessage().setHeader("Location", location);
})
.setBody(constant(""))
.endRest()
// 4. 换 token:/oauth/token
.post("/token").consumes("application/x-www-form-urlencoded")
.route()
.process(ex -> {
String clientId = ex.getIn().getHeader("client_id", String.class);
String clientSecret = ex.getIn().getHeader("client_secret", String.class);
String code = ex.getIn().getHeader("code", String.class);
// 简单 Basic 校验
String basic = ex.getIn().getHeader("Authorization", String.class);
if (basic == null || !basic.equals("Basic " + Base64.getEncoder()
.encodeToString((clientId + ":" + clientSecretMap.get(clientId)).getBytes()))) {
throw new IllegalArgumentException("invalid_client_auth");
}
String cachedClient = codeCache.getIfPresent(code);
if (cachedClient == null || !cachedClient.equals(clientId)) {
throw new IllegalArgumentException("invalid_code");
}
codeCache.invalidate(code);
// 生成 JWT 风格 access_token
String jwt = Jwts.builder()
.setSubject("user")
.claim("client_id", clientId)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 3600_000))
.signWith(SignatureAlgorithm.HS256, "secret".getBytes())
.compact();
ex.getMessage().setBody(Map.of(
"access_token", jwt,
"token_type", "Bearer",
"expires_in", 3600));
})
.marshal().json()
.endRest();
}
}
跑通步骤:
mvn spring-boot:run后,浏览器访问
http://localhost:8080/oauth/authorize?client_id=portal&redirect_uri=http://localhost:9000/callback&state=xyz- 输入 admin/admin123,回调后会拿到
code; - 用 Postman 向
http://localhost:8080/oauth/token发
POST x-www-form-urlencoded带上client_id=portal&client_secret=portal-secret&code=xxx
即可收到 JSON 格式的access_token。
至此,基于 Camel-undertow 的轻量级授权码服务器完成,全程无 Spring Security OAuth2,代码 <200 行,可打包成 FatJar 直接上云。
拓展思考
-
生产级加固
- 登录页换成 国密 SM2 加密密码 传输;
- 授权码和 access_token 存入 Redis 集群,解决多实例共享;
- 增加 refresh_token 路由,实现无感刷新;
- 用 camel-undertow 的 SSL 配置 强制 HTTPS,满足等保 2.0。
-
与微服务集成
- 把
token路由拆成独立camel-microservice,用 camel-kubernetes 做服务发现; - 网关侧用 camel-jetty/camel-undertow 写全局
AuthorizationFilter,通过 camel-http 调用本服务做 token 校验,实现 零侵入 的 API 统一认证。
- 把
-
性能调优
- undertow 的 IO 线程非常轻,路由里若调本地 DB,务必用 threads() 切业务线程池;
- 对
/oauth/authorize做 LRU 缓存 静态登录页,QPS 可提升 3 倍; - 用 camel-micrometer 输出
/actuator/metrics/camel.route指标,对接 Prometheus + Grafana,实现国内云厂商托管监控。
-
面试加分回答
如果面试官追问“为什么不用 Spring Security OAuth2”,可答:
“Spring Security OAuth2 已停止维护,新项目推荐 Spring Authorization Server,但依赖全家桶太重;Camel + Undertow 方案仅 3 个 Jar,可运行在边缘网关盒子或 Android 终端,符合国内很多政企项目‘轻量可审计’的硬性要求。”