如何使用Pac4j OAuth2与Undertow做集成测试?Mock用户获取Profile失败
解决Pac4j测试场景下FakeGitHubClient无法获取用户Profile的问题
问题根源
你的FakeGitHubClient仅实现了凭证提取和认证逻辑,但没有将认证后的UserProfile存入会话。ProfileManager.getProfile()是从会话中读取已认证的用户信息,当前测试会话中无任何profile数据,因此返回空Optional。
解决方案一:手动在测试中注入UserProfile到会话
如果仅需快速验证业务逻辑,可绕过FakeClient的认证流程,直接将测试用UserProfile存入会话:
// 在测试代码中创建WebContext与SessionStore后 val webContext = new UndertowWebContext(exchange) val sessionStore = FindBest.sessionStore(null, config, new UndertowSessionStore(exchange)) val profileManager = config.getProfileManagerFactory().apply(webContext, sessionStore) // 构造测试用GitHubProfile val testProfile = new GitHubProfile() testProfile.setId("test-github-123") testProfile.addAttribute("displayName", "Test User") // 将profile存入会话 profileManager.save(testProfile, true) // 后续调用getProfile即可获取到数据 val profileOpt = profileManager.getProfile().toScala
解决方案二:修复FakeGitHubClient的认证流程
若需模拟完整OAuth2认证流程,需调整FakeClient逻辑,确保触发Pac4j将profile存入会话的步骤:
class FakeGitHubClient(userProfile: UserProfile) extends OAuth20Client { setCallbackUrl("http://local.test") setClientName("GitHub") // 必须设置客户端名称,Pac4j用它关联会话中的profile override protected def internalInit(forceReinit: Boolean): Unit = { // 自定义凭证提取器,直接返回携带测试profile的凭证 defaultCredentialsExtractor((ctx, store) => { val creds = new TokenCredentials("fake-token") creds.setUserProfile(userProfile) ju.Optional.of(creds) }) // 自定义认证器,确保返回带profile的凭证 defaultAuthenticator((cred, ctx, store) => { cred.setUserProfile(userProfile) cred }) super.internalInit(forceReinit) } }
测试时需触发完整认证回调流程:
- 模拟用户访问认证端点(如
/auth/github) - 模拟回调请求到
/callback?client_name=GitHub - Pac4j会自动将认证后的profile存入会话,后续
ProfileManager.getProfile()即可获取数据
额外检查点
- 确保测试中的
UndertowExchange模拟正确,会话存储可正常读写 - 确认Pac4j配置中已用
FakeGitHubClient替换真实的GitHubClient
内容的提问来源于stack exchange,提问作者insan-e
相关产品推荐
相关产品推荐

