(已解决)如何获得使用Rest Assured验证Gmail API的访问令牌

问题描述 投票:0回答:1

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

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

我基本上有两个问题:

  1. 我应该如何在Google Cloud Platform中设置OAuth的API凭据,以便通过Rest Assured(如我们对邮递员所做的请求)来命中请求
  2. 什么是请求端点和方法。

到目前为止,我已经尝试过以下方法,这些方法引用了StackOverflow和其他博客上发布的各种解决方案:

  1. 方法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());
    }
    

结果:预期状态码为<200>,但为<400>。

方法2:

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());
        }

结果:预期状态码为<200>,但为<404>

方法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作为响应。

无需在这里对专家说,我对“放心的人”一无所知,只是想在黑暗中射箭以使事情正常进行。

我想要一种可靠的方法来生成OAuth令牌,然后每次运行测试。也可以随时指导我阅读任何现有文档。

这是我尝试访问的API文档的链接:https://developers.google.com/gmail/api/v1/reference/users/getProfile#auth

rest rest-assured web-api-testing
1个回答
0
投票

[在浏览了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,状态

    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. 最后一步是使用我们获得的令牌击中被测端点。

    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链接中。

© www.soinside.com 2019 - 2024. All rights reserved.