模拟用于测试Spring控制器的Keycloak令牌

5cg8jx4n  于 2023-01-12  发布在  Spring
关注(0)|答案(1)|浏览(131)

我想为我的spring控制器编写单元测试,我使用keycloak的openid流来保护我的端点。
在我的测试中,我使用@WithMockUser注解来模拟一个经过身份验证的用户,我的问题是我从主体的令牌中阅读userId,我的单元测试现在失败了,因为我从令牌中读取的userId为空;

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();
        }

有什么东西可以轻松地嘲笑KeycloakAuthenticationToken吗?

wj8zmpe1

wj8zmpe11#

@WithmockUser使用UsernamePasswordAuthenticationToken配置安全上下文。这对于大多数用例来说都很好,但当您的应用依赖于另一个身份验证实现时(就像您的代码一样),您必须构建或模拟正确类型的示例,并将其放入测试安全上下文:SecurityContextHolder.getContext().setAuthentication(authentication);
当然,您很快就会希望自动执行此操作,构建自己的注解或RequestPostProcessor
...或者...
取一个“现成的”,如这个lib of mine,它可从Maven-Central获得:

<dependency>
    <!-- just enough for @WithMockKeycloackAuth -->
    <groupId>com.c4-soft.springaddons</groupId>
    <artifactId>spring-security-oauth2-test-addons</artifactId>
    <version>3.0.1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <!-- required only for WebMvc "fluent" API -->
    <groupId>com.c4-soft.springaddons</groupId>
    <artifactId>spring-security-oauth2-test-webmvc-addons</artifactId>
    <version>3.0.1</version>
    <scope>test</scope>
</dependency>

您可以将其与@WithMockKeycloackAuth标注一起使用:

@RunWith(SpringRunner.class)
@WebMvcTest(GreetingController.class)
@ContextConfiguration(classes = GreetingApp.class)
@ComponentScan(basePackageClasses = { KeycloakSecurityComponents.class, KeycloakSpringBootConfigResolver.class })
public class GreetingControllerTests extends ServletUnitTestingSupport {
    @MockBean
    MessageService messageService;

    @Test
    @WithMockKeycloackAuth("TESTER")
    public void whenUserIsNotGrantedWithAuthorizedPersonelThenSecretRouteIsNotAccessible() throws Exception {
        mockMvc().get("/secured-route").andExpect(status().isForbidden());
    }

    @Test
    @WithMockKeycloackAuth("AUTHORIZED_PERSONNEL")
    public void whenUserIsGrantedWithAuthorizedPersonelThenSecretRouteIsAccessible() throws Exception {
        mockMvc().get("/secured-route").andExpect(content().string(is("secret route")));
    }

    @Test
    @WithMockKeycloakAuth(
            authorities = { "USER", "AUTHORIZED_PERSONNEL" },
            claims = @OpenIdClaims(
                    sub = "42",
                    email = "ch4mp@c4-soft.com",
                    emailVerified = true,
                    nickName = "Tonton-Pirate",
                    preferredUsername = "ch4mpy",
                    otherClaims = @Claims(stringClaims = @StringClaim(name = "foo", value = "bar"))))
    public void whenAuthenticatedWithKeycloakAuthenticationTokenThenCanGreet() throws Exception {
        mockMvc().get("/greet")
                .andExpect(status().isOk())
                .andExpect(content().string(startsWith("Hello ch4mpy! You are granted with ")))
                .andExpect(content().string(containsString("AUTHORIZED_PERSONNEL")))
                .andExpect(content().string(containsString("USER")));
    }

或MockMvc流畅API(请求后处理器):

@RunWith(SpringRunner.class)
@WebMvcTest(GreetingController.class)
@ContextConfiguration(classes = GreetingApp.class)
@ComponentScan(basePackageClasses = { KeycloakSecurityComponents.class, KeycloakSpringBootConfigResolver.class })
public class GreetingControllerTest extends ServletKeycloakAuthUnitTestingSupport {
    @MockBean
    MessageService messageService;

    @Test
    public void whenUserIsNotGrantedWithAuthorizedPersonelThenSecretMethodIsNotAccessible() throws Exception {
        mockMvc().with(authentication().roles("TESTER")).get("/secured-method").andExpect(status().isForbidden());
    }

    @Test
    public void whenUserIsGrantedWithAuthorizedPersonelThenSecretMethodIsAccessible() throws Exception {
        mockMvc().with(authentication().roles("AUTHORIZED_PERSONNEL")).get("/secured-method")
                .andExpect(content().string(is("secret method")));
    }

}

相关问题