【发布时间】:2020-03-09 03:42:00
【问题描述】:
我正在尝试使用 restAssured 验证 gmail API。根据文档,它需要使用 Key 和 OAuth2.0 进行身份验证。我最初使用 POSTMAN 并且能够生成访问令牌并随后点击请求以获得成功响应。现在我想用 Rest Assured 框架实现同样的效果。
我想在 testNG 框架的 beforeMethod/beforeTest 某处添加生成令牌的逻辑。
我基本上有两个问题:
- 我应该如何在 Google Cloud Platform 中为 OAuth 设置 API 凭据,以便通过 Rest Assured 来满足请求(就像我们为 Postman 所做的那样)
- 应该是什么请求端点和方法。
到目前为止,我已经尝试了以下方法,参考了 Stack Overflow 和其他博客上发布的各种解决方案:
-
方法一
public void oAuthToken() { Response res = given(). auth(). preemptive().basic("username", "password"). header("Content-Type","application/json"). queryParam("key","KeyGeneratedFromAPICedentials"). formParam("client_id","created an OAuth Client ID"). formParam("client_secret","created an OAuth Client Secret_ID"). formParam("grant_type","client_credentials"). when(). get("https://accounts.google.com/o/oauth2/auth"). //Getting this endpoint from JSON in OAuth Client ID created in google Cloud Platform then().assertThat().statusCode(200).extract().response(); System.out.println("This is the response : " +res.asString()); }
结果:预期的状态代码 但为 。
方法二:
public void oAuthToken() {
Response res = given().
auth().
preemptive().basic("username", "password").
header("Content-Type","application/json").
queryParam("key","KeyGeneratedFromAPICedentials").
formParam("client_id","created an OAuth Client ID").
formParam("client_secret","created an OAuth Client Secret_ID").
formParam("grant_type","client_credentials").
when().
get("https://oauth2.googleapis.com/token").
//Getting this endpoint from JSON in OAuth Client ID as Token_URI created in google Cloud Platform
then().assertThat().statusCode(200).extract().response();
System.out.println("This is the response : " +res.asString());
}
结果:预期状态代码 但为
方法3:
public void oAuthToken() {
RestAssured.baseURI="https://oauth2.googleapis.com";
Response res = given().
auth().preemptive().basic("Client_ID", "Client_Secret").
contentType("application/x-www-form-urlencoded").
formParam("grant_type","client_credentials").
formParam("scope","openid").
when().
get("/token").
then().assertThat().statusCode(200).extract().response();
System.out.println("This is the response : " +res.asString());
}
结果:再次得到 404 作为响应。
方法 4: 通过邮递员中的“生成访问令牌”获取访问令牌后直接传递访问令牌。
结果: 得到 403 作为响应。
不必对这里的专家说,我对 Rest Assured 很陌生,只是想在黑暗中射箭以使事情正常进行。
我想要一种在每次运行测试之前生成 OAuth 令牌的稳健方法。也请随时指导我查看任何现有文档。
这是我尝试访问的 API 文档的链接:https://developers.google.com/gmail/api/v1/reference/users/getProfile#auth
【问题讨论】:
标签: rest rest-assured google-apis-explorer web-api-testing