OAuth 2.0 Token request automation - stop request of new token after each REST Request run
- 5 years ago
Unfortunately this script calls for a token before each request (in a Load test, it brought down our Keycloak server and not the intended app server!)
What worked for us is the following script.
You need to add the jjwt library to Ready API to use it. You can download it here https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt/0.9.1 and just copy it to the bin/ext folder of your Ready API install directory.
// 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;
import io.jsonwebtoken.*;// Set up variables
def project = ModelSupport.getModelItemProject(context.getModelItem());
def authProfile = project.getAuthRepository().getEntry("TEST_ENV");
def oldToken = authProfile.getAccessToken();
def tokenType = TokenType.ACCESS;// Create a facade object
def oAuthFacade = new OltuOAuth2ClientFacade(tokenType);def currentTimePlus3min = new Date(System.currentTimeMillis() + 180 * 1000);
def expiry;try{
def index = oldToken.lastIndexOf('.')
def withoutSignature = oldToken.substring(0, index+1);
expiry = Jwts.parser().parse(withoutSignature).getBody().getExpiration();
}catch(e){
expiry = new Date(System.currentTimeMillis());;
}
log.info("Token Expiry"+expiry+" "+ "currentTimePlus3min"+ currentTimePlus3min);//If the Token will expire in the next 3 minuites get a new token
if(currentTimePlus3min > expiry ){// 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);
for(int i = 0; i<=3000; i++){
if(oldToken != authProfile.getAccessToken()){
break
}
sleep(1)
}
// Post the info to the log
log.info("Set new token: " + authProfile.getAccessToken());
}Hope this helps someone else. it will request a new token every 3 minutes.