@WithMockKeycloakAuth获取accesstoken作为承载字符串,用于MockMvc执行标头

问题描述

我有一项服务,并且Keycloak 11作为身份验证服务器。现在我要编写测试。为了模拟访问令牌,我使用@WithMockKeycloakAuth。这样效果很好,例如,当我担任坏角色时,我会遭到未经授权。现在我想用spring rest docs记录它,为此我必须添加acesstoken作为头字段(Bearer tokenAsBearerString)。由于有注释,因此将模拟令牌添加到SecurityContext中,我可以在执行mvc.perform之前将其提取。

@Test
    @Order(5)
    @WithMockKeycloakAuth(authorities = "ROLE_owner")
    void createProduct_RealmRoleOwner_HttpStatusCreated() throws Exception {

        SecurityContext context = SecurityContextHolder.getContext();
        KeycloakAuthenticationToken authentication =(KeycloakAuthenticationToken) context.getAuthentication();
        AccessToken token  =  authentication.getAccount().getKeycloakSecurityContext().getToken();

问题是我需要将accesstoken作为Bearer字符串表示形式。我对jwt主题还不是很熟悉,但是我希望如果我使用模拟的acces令牌并将其转换为jwt格式/ Base 64编码的String,标题应该是正确的。

此外:我正在通过docker在单独的网络中运行Keycloak容器,因此在运行自动化测试时无法访问它。因此,嘲笑将是唯一的解决方案。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)