Set Up API OAuth2 Authentication in Katalon Studio
To perform API testing on Salesforce using Katalon Studio, you 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 is to use an access token obtained through external tools or methods. Here’s how to set up authentication for Salesforce API testing in Katalon Studio.
Obtaining an Access Token for Salesforce
Before sending API requests to Salesforce, you must 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, and it’s one of the easiest ways for testing. Here’s how:
Get an Access Token with Salesforce CLI
Use the Salesforce CLI to get the access token (bearer token) for authenticating API requests.
-
Install or Update Salesforce CLI:
- If you already have Salesforce CLI installed, update it using the instructions in the documentation.
- If not, install the latest version of Salesforce CLI for your operating system.
- Verify your installation.
-
Log in to Your Developer Org:
sf org login web
A browser window will open to the Salesforce login page. Log in to your Developer Org with your credentials and allow access.
-
Get the Access Token: After logging in, retrieve the access token and instance URL using the following command:
sf org display
In the command output, make note of the Access Token and Instance URL. You’ll need these for making API requests.
Integrating Salesforce API with Katalon Studio
Now that you have your access token, here’s how to configure Katalon Studio for API testing with Salesforce.
Steps to Set Up Authentication in Katalon Studio
-
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. Configure the request URL, method, and other parameters for the Salesforce API you intend to test.
-
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 from Salesforce CLI in the token field.
-
Send API Requests:
- After setting up the authorization, 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.
-
Automate Token Refresh (Optional):
- If your testing session lasts longer than the token’s expiration time, you can implement a mechanism in Katalon (e.g., using Test Listeners or custom keywords) to refresh the token automatically.
-
Verify 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.
-
Security Best Practices:
- Store sensitive information such as access tokens securely (avoid hardcoding them). Use environment variables for this purpose, especially in CI/CD pipelines.
- Keep Salesforce API limits in mind to avoid exceeding them during testing.
Best Practices for OAuth Flow API in Test Automation
For test automation, you can set up an OAuth API flow to dynamically fetch tokens for your tests. Here’s a step-by-step guide to implementing a custom OAuth flow in Katalon Studio:
1. Custom .env Loader Function
This function loads environment variables from a .env
file where you can store sensitive information like client IDs, secrets, usernames, and passwords.
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.IOException
public class EnvironmentLoader {
@Keyword
static Map<String, String> loadEnvironmentVariables(String filename = ".env") throws IOException {
Map<String, String> envVars = new HashMap<>()
Path path = Paths.get(new File(".").getAbsolutePath()).getParent()
boolean found = false
while (path != null && Files.exists(path) && !found) {
Path possibleEnvPath = path.resolve(filename)
if (Files.exists(possibleEnvPath)) {
found = true
Files.readAllLines(possibleEnvPath).each { line ->
if (!line.startsWith("#") && line.contains("=")) {
def parts = line.split("=")
if (parts.length == 2) {
envVars.put(parts[0].trim(), parts[1].trim())
}
}
}
}
path = path.getParent()
}
System.getenv().each { key, value ->
if (!envVars.containsKey(key)) {
envVars.put(key, value)
}
}
if (envVars.isEmpty()) {
throw new IllegalStateException("No environment variables found.")
}
return envVars
}
}
This function reads environment variables from a .env
file and falls back to system variables if necessary. Use it to securely store sensitive data like API credentials.
2. OAuth2 Token Fetching Custom Function
This function dynamically fetches an OAuth2 token for API testing:
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.webservice.keyword.WSBuiltInKeywords as WS
import groovy.json.JsonSlurper
class OAuth2 {
@Keyword
def getOAuth2Token(String clientId, String clientSecret, String url) {
String body = "grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}"
List<TestObjectProperty> headers = Arrays.asList(
new TestObjectProperty("Content-Type", ConditionType.EQUALS, "application/x-www-form-urlencoded")
)
RequestObject requestObject = new RestRequestObjectBuilder()
.withRestUrl(url)
.withRestRequestMethod("POST")
.withHttpHeaders(headers)
.withTextBodyContent(body)
.build()
def response = WS.sendRequest(requestObject)
if (response.getStatusCode() == 200) {
def jsonResponse = new JsonSlurper().parseText(response.getResponseText())
return jsonResponse.access_token
} else {
println("Failed to retrieve OAuth2 token: HTTP Status = ${response.getStatusCode()}")
return null
}
}
}
This function sends a POST request to fetch the OAuth2 token dynamically. By using both custom functions, you can securely store and use tokens for API testing.
Conclusion
By following these steps, you can effectively set up OAuth2 authentication in Katalon Studio for testing Salesforce APIs. Additionally, integrating the custom environment loader and OAuth2 token-fetching functions will enhance your security and flexibility during testing.