Forum Discussion

davecoleman's avatar
4 years ago

OAuth 2.0 Token request automation - stop request of new token after each REST Request run

Hi all, I currently am running a Functional suite of tests (7 GET methods) which form the basis of a Load Test (LoadUI). I have implemented OAuth automation as per here
  • davecoleman's avatar
    4 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 and just copy it to the bin/ext folder of your Ready API install directory.

    // Import the required classes
    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;

    def index = oldToken.lastIndexOf('.')
    def withoutSignature = oldToken.substring(0, index+1);
    expiry = Jwts.parser().parse(withoutSignature).getBody().getExpiration();
    expiry = new Date(System.currentTimeMillis());;
    }"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
    for(int i = 0; i<=3000; i++){
    if(oldToken != authProfile.getAccessToken()){

    // Post the info to the log"Set new token: " + authProfile.getAccessToken());

    Hope this helps someone else. it will request a new token every 3 minutes.