我正在尝试从运行示例应用程序:
https://github.com/keycloak/keycloak-quickstarts/tree/latest/app-springboot
我收到错误消息:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of method setKeycloakSpringBootProperties in org.keycloak.adapters.springboot.KeycloakBaseSpringBootConfiguration required a bean of type 'org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver' that could not be found.
Action:
Consider defining a bean of type 'org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver' in your configuration.
Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud) 我想为我的弹簧控制器编写单元测试.我正在使用keycloak的openid流来保护我的端点.
在我的测试中,我使用@WithMockUser注释来模拟经过身份验证的用户.我的问题是我正在从校长的令牌中读取userId.我的单元测试现在失败了,因为userId我从令牌读取的是null;
if (principal instanceof KeycloakAuthenticationToken) {
KeycloakAuthenticationToken authenticationToken = (KeycloakAuthenticationToken) principal;
SimpleKeycloakAccount account = (SimpleKeycloakAccount) authenticationToken.getDetails();
RefreshableKeycloakSecurityContext keycloakSecurityContext = account.getKeycloakSecurityContext();
AccessToken token = keycloakSecurityContext.getToken();
Map<String, Object> otherClaims = token.getOtherClaims();
userId = otherClaims.get("userId").toString();
}
Run Code Online (Sandbox Code Playgroud)
有什么可以轻易嘲笑的KeycloakAuthenticationToken吗?
我知道,关于这个问题,这里和这里已经有类似的问题,但提出的每个解决方案都未能帮助我。大多数答案中也提到了这个库,但是(恕我直言)我想避免依赖外部库只是为了能够测试一个简单的控制器。
因此,我有一个非常简单的 api,可以使用 keycloak 生成的不记名令牌进行访问,我想测试控制器。沿着这些思路:
@Test
@DisplayName("Should be ok")
@WithMockUser
void whenCalled_shouldBeOk() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
mockMvc.perform(
post("/api/url/something")
.content("{}")
.contentType(APPLICATION_JSON)
.with(authentication(authentication))
).andExpect(status().isOk());
}
Run Code Online (Sandbox Code Playgroud)
问题是我总是会得到一个空指针异常,因为KeycloakDeploymentBuilder它缺少适配器配置。在我们的 SecurityConfig 中,我们扩展KeycloakWebSecurityConfigurerAdapter并执行应用程序工作所需的所有配置,但我未能在测试中模拟/绕过此过程。通常我会在测试中使用 @WithMockUser 注释找到解决此身份验证问题的方法(当不使用 keycloak 时),但这次不行。
没有办法模拟适配器或过滤进程来绕过这个问题吗?
我已经尝试了其他问题(图书馆除外)中回答的所有内容,但没有运气。如果您有任何可能有帮助的线索,或者至少为我指明了正确的方向(因为这可能是由于我缺乏对 Spring 安全性的了解),我将非常感激。