Wednesday 7 May 2014

Groovy Script RESTClient example with an OAuth client

In my first look at Groovy script for SoapUI yesterday i needed to access a restful service and pull back some json content which looks like this:

access_token:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3Mi8m6BYc, expires_in:35999, refresh_token:6952f91f508c4f9f9

here is the script code for my project:



// Grab and imports     
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7')
@Grab(group='oauth.signpost', module='signpost-core', version='1.2.1.2')
@Grab(group='oauth.signpost', module='signpost-commonshttp4', version='1.2.1.2')
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.*
import groovyx.net.http.*
import static groovyx.net.http.Method.*

def client = new RESTClient('https://identity.myService.net/idsrv/issue/oauth2/token', ContentType.URLENC ) 
client.defaultRequestHeaders.'Authorization' = "Basic ENCRYPTED_CONTENT_HERE"
client.setContentType('application/json') // important for accessing the json response

// Perform Http Post with url encoded content
def response = client.post(body: ["grant_type":"password", "username":"myusername", "password":"mypassword","scope":"http://myservice.net"]) 

// access response examples
println response.getStatus()
println response.getContentType() 

if (response.getStatus() != 200)
{
    println "Unsuccessful call!!"
}
else
{
      
    def r =  response.getData().access_token // this accesses the json access_token
    
    // set my global property
    //com.eviware.soapui.SoapUI.globalProperties.setPropertyValue( "Authorization", "Bearer " + r )    
}