Forum Discussion

SiKing's avatar
SiKing
Community Expert
2 years ago

Problems with refresh OAuth2 token

For our service we are using OAuth2 for authorization. I have defined an OAuth2 profile in the Auth Manager. When I click the Get Access Token button manually everything works as expected: a new ...
  • SiKing's avatar
    2 years ago

    I seem to remember I had already dealt with this sometime in the past. Oh right: 5 years ago! It's a shame this shortcoming still exists in ReadyAPI. 😞

     

    Yki Here is a slightly improved(?) version on that script:

     

    // Name: 'Forced token update'
    // Event: 'SubmitListener.beforeSubmit'
    // Target: '${=submit.request.authType.asBoolean()}' filters only test steps that have Authorization as an option
    
    // https://support.smartbear.com/readyapi/docs/requests/auth/types/oauth2/automate/index.html#on-request
    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 com.eviware.soapui.config.AccessTokenStatusConfig
    
    def project = ModelSupport.getModelItemProject(context.getModelItem())
    
    def authProfile = project.authRepository.getEntry("!YOUR AUTH PROFILE NAME!")
    
    if(authProfile.accessTokenStatus != AccessTokenStatusConfig.RETRIEVED_FROM_SERVER) {
    	
    	def oAuthFacade = new OltuOAuth2ClientFacade(TokenType.ACCESS)
    	
    	oAuthFacade.requestAccessToken(authProfile, true, true)
    	
    	// Access token retrieval may take time.
    	def stopLoop = 0	// loop counter to prevent infinite loops in case of problems
    	while(authProfile.accessTokenStatus != AccessTokenStatusConfig.RETRIEVED_FROM_SERVER && stopLoop++ < 6)
    		sleep(5)
    	
    	log.info("Set new token: ${authProfile.accessToken}")
    }