Skip to main content

Quality Assurance

A Guide to OAuth 2.0 Authorization Code Grant in API Testing using Rest Assured

Istock 1435220822

Understanding OAuth 2.0: The Gatekeeper to Secure API Access

In API testing, ensuring secure and authorized access to protected resources is paramount. This is where OAuth 2.0, an industry-standard authorization framework, comes into play. It acts as a robust mechanism for granting temporary access tokens to applications. It enables them to interact with APIs on behalf of users without directly obtaining their credentials. This approach enhances both security and user experience.

In this blog, we will explore how to perform OAuth 2.0 authorization code flow using REST Assured in API testing.

Beyond Authorization Code: Exploring the Grant Landscape of OAuth 2.0

While the Authorization Code flow is a commonly used approach, OAuth 2.0 offers a variety of grant types to cater to diverse authorization scenarios:

  • Authorization Code Grant: (This is the focus of this blog!) Ideal for web applications and server-side applications where you can safely store client secrets.
  • Implicit Grant: This is suitable for public clients, such as JavaScript applications running in web browsers, where client secrets are not secure.
  • Resource Owner Password Grant: This is used in limited situations when user consent is readily available, and client secrets can be securely stored.
  • Client Credentials Grant: Designed for machine-to-machine (M2M) communication, where applications directly authenticate with the authorization server using client credentials

Real-World Example: Unlocking the Power of Authorization Code in Action

Popular websites like Facebook, Google, and GitHub utilize the Authorization Code flow to allow third-party applications to access user data with their consent.

For instance, when you log in to a fitness app using your Facebook credentials. Yoou grant the app temporary access to your fitness data on Facebook without sharing your actual Facebook password. The app follows the Authorization Code flow behind the scenes to obtain the necessary access token.

The Flow in Action: A Step-by-Step Guide

  1. Initiating the Authorization Request: The client constructs a request containing parameters like client ID, redirect URI, and requested scopes to the authorization server.
  2. Redirecting the User: The user is redirected to the authorization server’s login page. User authenticate and grant or deny the requested permissions.
  3. Authorization Code Delivery: Upon consent, the authorization server redirects the user to the client’s redirect URI with an authorization code as a query parameter.
  4. Token Request: The client sends a request to the token endpoint(resource server), including the authorization code and client credentials. The client exchanges the request for an access token.
  5. Access Token Issuance: If the credentials are valid, the server grants the client an access token (and optionally a refresh token).
  6. API Access: The client includes the access token in the authorization header for subsequent API requests, enabling authorized interaction with the protected resources.

Example Website Using OAuth 2.0 Authorization Code Grant

Let’s consider an example website, “example.com,” that uses an OAuth 2.0 authorization code grant for authentication. The website’s authorization endpoint is https://example.com/oauth/authorize, and the token endpoint (resource) is https://example.com/oauth/token.

Note: The API contract is usually available for testing APIs. It contains all the required information, such as URLs, client IDs, client secrets, redirect URIs, etc.

Performing OAuth 2.0 Authorization Code Flow with REST Assured

To perform OAuth 2.0 authorization code flow using REST Assured, we need to follow these steps:

  1. Obtain Authorization Code: Redirect the user to the authorization server’s authorization endpoint to obtain an authorization code.
  2. Exchange Authorization Code for Access Token: Use the authorization code to request an access token from the authorization server’s token endpoint.
  3. Use Access Token: Use the access token to authenticate API requests.

Sample REST Assured Code for OAuth 2.0 Authorization Code Flow

Below is the Rest Assured code for the sample flow with the explanation:

ublic class OAuth2_AuthCode {

    public static void main(String[] args) throws InterruptedException {
        
          // STEP-1: Obtain Authorization Code
          //paste AUTHORIZATION server/url in browser
          WebDriverManager.chromedriver().setup(); 
          ChromeDriver driver = new ChromeDriver();
          driver.get("https://example.com/oauth/authorize"); 
          
          //sign in > ENTER email> ENTER password >CLICK submit
          driver.findElement(By.cssSelector("input[type='email']")).sendKeys("test@test.com");
          driver.findElement(By.cssSelector("input[type='email']")).sendKeys(Keys.ENTER); Thread.sleep(3000);
          driver.findElement(By.cssSelector("input[type='password']")).sendKeys("MohimPassword");
          driver.findElement(By.cssSelector("input[type='password']")).sendKeys(Keys.ENTER); Thread.sleep(3000);
          
          //get URL containing CODE 
         String url = driver.getCurrentUrl();
        
        //extract code from it using java functions
        String partial = url.split("code=")[1];
        String code =partial.split("&scope")[0];
        System.out.println(code);
        
        //STEP-2: Exchange Authorization Code for Access Token from Token Endpoint(resource) server/url
        
        //construct request as per the api contract include the code and add required details like id, secret, uri 
        String accessTokenResp = given().urlEncodingEnabled(false).queryParam("code", code)
                .queryParam("client_id", "692183103107-p0m7ent2hk7suguv4vq22hjcfhcr43pj.apps.googleusercontent.com")
                .queryParam("client_secret", "erZOWM9g3UtwNRj340YYaK_W")
                .queryParam("redirect_uri", "https://example.com/")
                .queryParam("grant_type", "authorization_code")
                .when().post("https://example.com/oauth/token")
                .then().log().all().extract().response().asString();
        
        //pass response into JsonPath class object to read json response and extract access_token from it
       
        JsonPath jp = new JsonPath(accessTokenResp);
        String token = jp.getString("access_token");
        
        //Finally execute GET Request using redirect url
        String response = given().queryParam("access_token",token)
                        .when().post("https://example.com/")
                        .then().log().all().extract().response().asString();
        
        System.out.println(response);   
        
    }
}

In this code snippet, we have used example URLs and sample data to understand the flow using Rest Assured.

Conclusion

In conclusion, OAuth 2.0 authorization code flow is a secure and widely used method for API authentication. By using REST Assured, you can easily perform OAuth 2.0 authorization code flow in your API tests. It ensures that your APIs are secure and compliant with OAuth 2.0 standards.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Himanshu Pawar

Himanshu Pawar works in Quality assurance at Perficient, based out of India. He is currently working on Adobe technologies. Himanshu is a technology enthusiast passionate about automation and automation tools. He constantly seeks opportunities to learn and explore new technologies.

More from this Author

Categories
Follow Us