【问题标题】:How to automatically get Bearer Token using REST Assured如何使用 REST Assured 自动获取承载令牌
【发布时间】:2018-10-01 22:07:14
【问题描述】:

我目前正在使用 Postman 来生成我在自动化测试中使用的 Bearer Token。现在我也想使用 Java 中的 REST Assured 来自动化承载令牌生成过程。请帮我。谢谢。

Response response =
      given()
          .auth()
          .oauth(
              "n0pCrq5SPgraZ3CyY0Nd",
              "xvvx-LVd5dszLi9OO_1qjbU4eUQ4dXwLrDZN7oioSITr_EXrgsyyOvPvZmv85Ew2",
              "",
              "",
                  "HMAC-SHA256")
          .when()
          .get(url)
          .then()
          .contentType(ContentType.JSON)
          .extract()
          .response();

【问题讨论】:

  • 请发布您的 POSTMAN 设置的屏幕截图,您必须生成不记名令牌,我们可以提供帮助

标签: java oauth postman rest-assured bearer-token


【解决方案1】:

这是有效的。谢谢@wilfred 克莱门特。

public static String getOauthToken(String consumerKey, String consumerSecret, String endpoint ) {

log.info("GET ACCESS TOKEN=" + endpoint);
URI uri = null;
try {
  uri = new URI(endpoint);
} catch (URISyntaxException e) {
  log.error("Not proper oauth url=" + endpoint);
  throw new RuntimeException(e);
}

ValidatableResponse res = given()
        .header("Content-Type", "application/json")
        .auth().oauth(consumerKey,
                consumerSecret,
                "",
                "")
        .body("{\"grantType\": \"client_credentials\"}").when().post(uri).then();

int responseCode = res.extract().statusCode();

if (HttpURLConnection.HTTP_OK == responseCode) {
  String token = res.extract().jsonPath().get("accessToken").toString();
  log.info("Auth token=" + token);
  return token;
} else {
  String msg = "Access token retrieve failed. Http response code=" + responseCode;
  log.error(msg);
  throw new RuntimeException(msg);
}

}

【讨论】:

    猜你喜欢
    • 2021-03-02
    • 2019-07-04
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 2019-10-08
    • 2019-09-28
    • 1970-01-01
    相关资源
    最近更新 更多