【问题标题】:How to request JWT Token from KeyCloak via Java/Kotlin API如何通过 Java/Kotlin API 从 KeyCloak 请求 JWT 令牌
【发布时间】:2020-08-14 11:11:35
【问题描述】:

我想要的是在单元测试中来自我的 KeyCloak-Server 的 JWT-Token 来测试我的 Rest-API

如何通过 Java-API 检索 JWT-Token??? 我知道有“已安装的适配器”https://github.com/keycloak/keycloak/blob/master/adapters/oidc/installed/src/main/java/org/keycloak/adapters/installed/KeycloakInstalled.java

但是这个适配器只能通过浏览器或命令行登录。

我正在寻找类似 MyAdapter.login(username, password)

【问题讨论】:

    标签: java kotlin keycloak


    【解决方案1】:

    在下面找到可用于测试的代码。

    代码基本上是调用 OIDC token 端点来检索访问令牌。

    假设有一个名为 tester1 的用户只能使用密码登录。

    客户端还需要密码。但客户端也可以配置为无需密码即可工作。

    // data for token request
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "password");
    params.add("client_id", "yourclient");
    params.add("username", "tester1");
    params.add("password", "secret");
    
    // construct token request (including authorization for client(
    RequestEntity<MultiValueMap<String, String>> authRequest = RequestEntity
        .post(new URI("https://keycloak.domain.com/auth/realms/yourrealm/protocol/openid-connect/token"))
        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
        .accept(MediaType.APPLICATION_JSON)
        .header("Authorization", httpBasicAuthorization("yourclient", "secret-client-credential"))
        .body(params);
    
    // execute request and test for success
    TestRestTemplate restTemplate = new TestRestTemplate();
    ResponseEntity<String> response = restTemplate.exchange(authRequest, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertTrue(response.getHeaders().getContentType().isCompatibleWith(MediaType.APPLICATION_JSON));
    
    // extract access token (JWT) from response
    JacksonJsonParser jsonParser = new JacksonJsonParser();
    final String accessToken = jsonParser.parseMap(response.getBody()).get("access_token").toString();
    

    【讨论】:

      猜你喜欢
      • 2018-07-30
      • 2017-10-21
      • 2018-04-09
      • 2019-07-09
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 2021-10-18
      相关资源
      最近更新 更多