Automating token retrieval consists of two parts - automating user interactions with the web page and calling the automation scripts when they are needed. This topic describes how you can handle both parts.
Retrieving a Token Automatically
To retrieve an OAuth 2.0 token, ReadyAPI uses JavaScript to simulate user actions against the web page. As long as the page is not changed, ReadyAPI will be able to retrieve the token without user interaction.
Authorization
Consent Code
If you need to log in, Google asks for your permission on a separate page. Scripts are bound to the page they are executed on, so you need to make sure this script is added to the Page 2 editor. If you enter both the login and the password, add it to the Page 3 editor, as well. It is the same consent script as the one used in the sample above.
JavaScript
function consent() {
if (document.getElementById('submit_approve_access')){
document.getElementById('submit_approve_access').click();
}
}
window.setInterval(consent, 100);
Calling the Automated Retrieval Procedure
The code above interacts with a web page to get an access token. It does not check if ReadyAPI is using an up-to-date version of the token or whether an updated version is needed. Use event handlers to call the update script when needed, for example, before each request is made or before project execution starts. For better stability, we recommend that you use the SubmitListener.beforeSubmit
event that will execute the code before the request body is formed.
The code below checks whether an access token is up-to-date and retrieves a new one if necessary.
![]() |
If you are using OAuth 2.0 Azure authentication, replace the OltuOAuth2ClientFacade class in the script with the OltuOAuth2AzureClientFacade class. |
Groovy
// Import the required classes
import com.eviware.soapui.impl.rest.actions.oauth.OltuOAuth2ClientFacade;
import com.eviware.soapui.support.editor.inspectors.auth.TokenType;
import com.eviware.soapui.model.support.ModelSupport;
// Set up variables
def project = ModelSupport.getModelItemProject(context.getModelItem());
def authProfile = project.getAuthRepository().getEntry("OAuth 2");
def oldToken = authProfile.getAccessToken();
def tokenType = TokenType.ACCESS;
// Create a facade object
def oAuthFacade = new OltuOAuth2ClientFacade(tokenType);
// Request an access token in headless mode
oAuthFacade.requestAccessToken(authProfile, true, true);
// Wait until the access token gets updated
while(oldToken == authProfile.getAccessToken()) {
}
//The sleep method can be used instead of a while loop
//sleep(3000);
// Post the info to the log
log.info("Set new token: " + authProfile.getAccessToken());
See Also
About Automating Token Retrieval
Using the Automated Token Script Editor
Automating Token Retrieval