【问题标题】:How to get the access token for validating Google API /Gmail API using Rest Assured如何使用 Rest Assured 获取用于验证 Google API /Gmail API 的访问令牌
【发布时间】:2020-03-09 03:42:00
【问题描述】:

我正在尝试使用 restAssured 验证 gmail API。根据文档,它需要使用 Key 和 OAuth2.0 进行身份验证。我最初使用 POSTMAN 并且能够生成访问令牌并随后点击请求以获得成功响应。现在我想用 Rest Assured 框架实现同样的效果。

我想在 testNG 框架的 beforeMethod/beforeTest 某处添加生成令牌的逻辑。

我基本上有两个问题:

  1. 我应该如何在 Google Cloud Platform 中为 OAuth 设置 API 凭据,以便通过 Rest Assured 来满足请求(就像我们为 Postman 所做的那样)
  2. 应该是什么请求端点和方法。

到目前为止,我已经尝试了以下方法,参考了 Stack Overflow 和其他博客上发布的各种解决方案:

  1. 方法一

    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


    【解决方案1】:

    在浏览了 N 个博客并尝试尽可能多地获取信息后,我终于能够想出一个解决方案,该解决方案在此过程中也有助于理解实际问题。

    这里的主要问题是处理 OAuth2.0 身份验证以访问我以错误方式执行的 Gmail API。 Google OAuth 基本上要求我们获取一个代码,我们可以使用该代码请求它向我们发送一个令牌。然后需要将令牌作为身份验证发送到我们正在测试的 API 端点以获得所需的响应。

    您可以先在 Google Cloud Platform 中设置应用凭据。详细步骤请参考这个答案:Using Postman to access OAuth 2.0 Google APIs

    上述步骤将为您提供重要参数,例如:Client_ID、Client_Secret、auth_url、redirect_uri。

    以下是我们从这里开始需要遵循的步骤:

    1. 从这些参数构造 AuthURL:BaseURI,Resource,scope,auth_url, client_id,responseType,redirect_uri,state

      public static void constructAuthenticationURL(String BaseURI, String Resource,String scope,
      String auth_url,String client_id,String responseType,String redirect_uri,String state) { 
      
      URL = BaseURI+Resource+"?scope="+scope+"&auth_url="+auth_url+"&client_id="+client_id+
          "&response_type="+responseType+"&redirect_uri="+redirect_uri+"&state="+state;
      
          }
      

    BaseURI - https://accounts.google.com

    资源 - /o/oauth2/v2/auth

    范围 - 来自 API 文档

    responseType - 代码

    状态 - 空

    1. 现在我们需要使用 Selenium 在浏览器中点击此 URL 并输入我们的用户名和密码。我们将看到一个空白屏幕,其中 URL 在“&code=”前面有代码。

       public static void getCodeThroughBrowserAuthentication(String Username,String Password) throws Exception {
          driver.get(URL);
          wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector
          ("input[type='email']"))).sendKeys(Username);
          driver.findElement(By.xpath("//span[text()='Next']")).click();
          wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector
          ("input[type='password']"))).sendKeys(Password);
          driver.findElement(By.xpath("//span[text()='Next']")).click();
          Thread.sleep(10000);
          String[] arr =  driver.getCurrentUrl().split("&code=");
          String code[] = arr[1].split("&scope=");
          //Store the Browser Code in a Variable to use it in Step 3
      }
      

    我使用 split() 从完整的 URL 中获取代码。

    1. 现在我们需要使用此代码来获取 AccessToken(Bearer) 以使用它来验证对实际端点的请求。

      public static void getBearerAccessToken() {
      RestAssured.baseURI="https://www.googleapis.com";
      Response res = given().urlEncodingEnabled(false)
      .queryParam("code", "Enter Browser code from previous step.")
      .queryParam("client_id", "Client ID from Google Cloud Platform")
      .queryParam("client_secret", "Client Secret ID from Google Cloud Platform")
      .queryParam("redirect_uri", "The one you have entered while setting up the App credentials")
      .queryParam("grant_type","authorization_code").
      when()
      .post("/oauth2/v4/token").
      then()
      .assertThat().statusCode(200).extract().response();
      
      System.out.println("The response with Access Token is : " +res.asString());
      
      JsonPath json = res.jsonPath();
      //Storing AccessToken in a Variable
      AccessToken = json.get("access_token");
      }
      
    2. 最后一步是使用我们获得的 Token 来访问被测端点。

      public void getUserProfile(String email,String AccessToken) {
      RestAssured.baseURI="https://www.googleapis.com";
      Response res = given().
      auth().preemptive().oauth2(Access Token //Pass the Value of Access Token from Previous Step).
      header("Content-Type","application/json").
      queryParam("key","Setup an API Credentials Key on Google Cloud Platform.").
      
      when().
      get("/gmail/v1/users/"+email+"/profile").
      
      then().assertThat().statusCode(200).extract().response();
      
      System.out.println("User profile response : " +res.asString());
      }
      

    如果有人需要更清晰的图片,我也会尽快添加指向 gitHub repo 链接的链接。

    【讨论】:

    • 你有代码示例吗?主要是为了了解所涉及的依赖项/库。谢谢!
    • 我将不得不搜索进行这些更改的 gitHub 存储库,将尝试在此处搜索并添加链接。但是,如果您添加 Java、Selenium 和 Rest Assured 依赖项,您应该可以继续使用。
    • 我认为您可以跳过硒步骤。获得授权码或刷新令牌后,您仍然可以放心地为您获取新的访问令牌。刷新令牌不会过期,因此如果您已经拥有它们,则无需再次执行。您可以通过浏览器手动检索授权码,如stackoverflow.com/a/66940682/6654475 所述,并使用它来获取刷新码。
    猜你喜欢
    • 2016-07-12
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 2018-02-12
    相关资源
    最近更新 更多