模拟Keycloak令牌以测试Spring控制器 [英] Mocking a Keycloak token for testing a Spring controller

查看:236
本文介绍了模拟Keycloak令牌以测试Spring控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的弹簧控制器编写单元测试.我正在使用keycloak的openid流保护我的端点.

I want to write unit tests for my spring controller. I'm using keycloak's openid flow to secure my endpoints.

在测试中,我使用@WithMockUser注释模拟经过身份验证的用户.我的问题是我正在从主体的令牌中读取userId.我的单元测试现在失败了,因为我从令牌中读取的userId为空;

In my tests I'm using the @WithMockUser annotation to mock an authenticated user. My problem is that I'm reading the userId from the token of the principal. My unit test now fails because the userId I read from the token is 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();
        }

有什么东西可以轻松模拟KeycloakAuthenticationToken吗?

Is there anything to easily mock the KeycloakAuthenticationToken?

推荐答案

添加以下内容后,我可以进行测试:

I was able to test after adding the following things:

  1. 添加一些字段:

  1. Add some fields:

@Autowired

    private WebApplicationContext context:
    private MockMvc mockMvc;

  • 在我的@Before setup()方法中:

  • In my @Before setup() method:

    mockMvc = MockMvcBuilders.webAppContextSetup(context)
       .alwaysDo(print())
       .apply(springSecurity())
       .build(); 
    

  • 在我的测试方法中:

  • Inside my test method:

    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    

  • 当我将authentication对象传递给从密钥斗篷令牌中读取声明的方法时,我可以运行测试而没有任何问题.

    When I pass the authentication object to the method where I read the claims from the keycloak token I can run the test without any problems.

    P.S.不要忘记@WithMockUser批注

    P.S. Don't forget the @WithMockUser annotation

    这篇关于模拟Keycloak令牌以测试Spring控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆