Set Up API OAUTH2 Authentication in Katalon Studio

To perform API testing on Salesforce using Katalon Studio, you’ll need to authenticate to access Salesforce’s REST API. While you can create and authenticate with your own connected app, a more straightforward approach for testing purposes involves using an access token obtained through external tools or methods. Here’s how you can set up authentication for Salesforce API testing in Katalon Studio, adapting from the initial Salesforce CLI-focused approach.

Obtaining an Access Token for Salesforce in the cli

Before sending API requests to Salesforce, secure an access token to authenticate your requests. This token, often referred to as a “bearer token,” is crucial for authorization. Salesforce CLI is a common method to obtain this token, although there are other methods this is the easiest way, and thus will explain it in this lesson

Get an Access Token with Salesforce CLI

Use the access token (also known as a “bearer token”) that you get from Salesforce CLI to authenticate cURL requests.

  1. Install or update Salesforce CLI. .
  • If you already have Salesforce CLI installed, update it using the instructions in Update Salesforce CLI.
  • If you need to Install Salesforce CLI, install the latest version for your operating system.
  • Verify Your Installation.
  1. Log in to your Developer org with Salesforce CLI.
sf org login web

A browser opens to https://login.salesforce.com.

  1. In the browser, log in to your Developer org with your user’s credentials.
  2. In the browser, click Allow to allow access. At the command line, you see a similar confirmation message.
  1. At the command line, get the access token by viewing authentication information about your org.

For example:

Example command output:

In the command output, make note of the long Access Token string and the Instance Url string. You need both to make cURL requests.

How about integrate this with Katalon

Steps to Set Up Authentication in Katalon Studio

  1. Configure Katalon Studio for API Testing:
  • Launch Katalon Studio and create or open your project.
  • Navigate to Object Repository and create a new RESTful request object. Here, you’ll configure the request URL, method, and other parameters for the Salesforce API you intend to test.
  1. Set Up Authentication:
  • In the request object configuration, go to the Authorization tab.
  • Select Bearer Token from the type dropdown.
  • Enter the access token you obtained earlier in the token field. Ensure this token is securely stored and not hardcoded in your test scripts for security reasons.

  1. Sending API Requests:
  • After setting up the authorization, you can configure the rest of your API request, including headers, body content (if applicable), and query parameters.
  • Use Katalon’s built-in functions to send the request and verify the response. This can involve checking the response status code, parsing response data, and validating it against expected values.
  1. Automate Token Refresh (Optional):
  • If your testing session extends beyond the lifespan of a single access token, implement a mechanism in Katalon (e.g., through Test Listeners or custom keywords) to refresh the token as needed automatically.
  1. Verify Your Setup:
  • Run your configured API request to ensure that the authentication is correctly set up and that you can successfully communicate with Salesforce’s API. 6 Security and Best Practices:
  • Always secure sensitive information such as access tokens. And for CICD it is is also important to store password information in variables outse the workspace/project scope. For this I created a small custom function which will be explained in the paragraph below
  • Keep your Salesforce API limits in mind to avoid exceeding them during testing. By following these steps, you can set up Salesforce API authentication in Katalon Studio, enabling you to perform comprehensive API testing on your Salesforce applications.

Best practice Set up Oauth flow API for testautomation

For testautomation purposes you can also opt for a Oauth api flow solution. The workinstruction I created in my blog “Setup oauth api client in Salesforce”

When this is defined you can use 2 custom functions I created for this

  1. A custom .env custom function to store sensitive information outside of the project
package environment

import com.kms.katalon.core.annotation.Keyword
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.io.FileNotFoundException
import java.io.IOException

public class EnvironmentLoader {

	/**
	 * Attempts to load environment variables from a .env file or falls back to system environment variables.
	 * @param filename Name of the .env file.
	 * @return Map containing the loaded environment variables.
	 * @throws IOException If the .env file cannot be read.
	 */
	@Keyword
	static Map<String, String> loadEnvironmentVariables(String filename = ".env") throws IOException {
		Map<String, String> envVars = new HashMap<>()
		String currentDir = new File(".").getAbsolutePath().substring(0, new File(".").getAbsolutePath().length() - 1)
		Path path = Paths.get(currentDir)
		boolean found = false

		// Try to find and load the .env file
		while (path != null && Files.exists(path) && !found) {
			Path possibleEnvPath = path.resolve(filename)
			if (Files.exists(possibleEnvPath)) {
				found = true
				List<String> lines = Files.readAllLines(possibleEnvPath)
				lines.each { line ->
					// Use Groovy's `each` instead of `forEach`
					if (!line.startsWith("#") && line.contains("=")) {
						def parts = line.split("=")
						if (parts.length == 2) {
							envVars.put(parts[0].trim(), parts[1].trim())
						}
					}
				}
			}
			path = path.getParent()
		}

		// Fallback to system environment variables if .env file not found or as supplement
		System.getenv().each { key, value ->
			// Use Groovy's `each` for consistency
			if (!envVars.containsKey(key)) {
				// Only add if not already defined by .env file
				envVars.put(key, value)
			}
		}

		if (envVars.isEmpty()) {
			throw new IllegalStateException("No environment variables found.")
		}

		return envVars
	}
}

What it does, you can put a .env and store there key value pairs like clientids/clientsecret usernames and passwords, and it will be picked up within your project.

This script should always be part of your flow when doing apitests

Second a oauth2 api custom function is created so that the katalon user dynamically can fetch its token.

package oauthflowapi
import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.testobject.RequestObject
import com.kms.katalon.core.testobject.RestRequestObjectBuilder
import com.kms.katalon.core.testobject.TestObjectProperty
import com.kms.katalon.core.testobject.ConditionType
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
import groovy.json.JsonSlurper
class OAuth2 {
	@Keyword
	def getOAuth2Token(String clientId, String clientSecret,String url) {
		// Define the request URL
		// Define the request body with actual clientId and clientSecret
		String body = "grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}"
		// Define the request headers
		List<TestObjectProperty> headers = Arrays.asList(
				new TestObjectProperty("Content-Type", ConditionType.EQUALS, "application/x-www-form-urlencoded")
				)
		// Create the request object using RestRequestObjectBuilder
		RequestObject requestObject = new RestRequestObjectBuilder()
				.withRestUrl(url)
				.withRestRequestMethod("POST")
				.withHttpHeaders(headers) // Use the list of TestObjectProperty
				.withTextBodyContent(body)
				.build()
		// Send the request and receive the response
		def response = WS.sendRequest(requestObject)
		// Check if the request was successful
		if (response.getStatusCode() == 200) {
			// Parse the JSON response to extract the access token
			def jsonResponse = new JsonSlurper().parseText(response.getResponseText())
			return jsonResponse.access_token
		} else {
			println("Failed to retrieve OAuth2 token: HTTP Status = ${response.getStatusCode()}")
			return null
		}
	}
}

If you use both custom functions in combination you can use the secrets stored locally and use this for test your api. In row 39 the token will be obtained

Please check out the delete function in my katalon testcase

This delete function will delete all items based on the select query in the former request and thus a fine example of managing the testdata with katalon and salesforce. If you check the query it is empty now while all other accounts besides learnauto still exist