获取令牌并将其作为其他步骤的授权标头的值发送

时间:2017-03-01 08:29:42

标签: json rest groovy soapui ready-api

从Post请求中获取令牌后,如下所示:

{ "access_token": "12345", "expires_in": 3600, "token_type": "Bearer" } 

我想在不同的TestSteps标头值中使用此标记。

例如,我收到此令牌后我必须发出GET请求,并且它在标题中有 - > Authentification : Bearer + token_value

那么我可以编写一个GroovyScript或其他东西来自动生成吗?我正在使用ReadyApi。

此致 阿德里安

2 个答案:

答案 0 :(得分:0)

为收到上述回复的同一步骤添加Script Assertion

脚本断言这将从响应中获取值并创建项目属性并设置检索到的值。

//Check if the response is empty or null
assert context.response, "Response is null or empty"
def json = new groovy.json.JsonSlurper().parseText(context.response)
def token =  "${json.token_type} ${json.access_token}" as String
log.info "Token will be: ${token}"
//Assing the value at project level property TOKEN
context.testCase.testSuite.project.setPropertyValue('TOKEN', token)

现在需要动态地将值设置为每个传出请求的标头。即,添加Authorization标头及其SOAPREST请求类型步骤的值。为此,将使用Events功能。 添加SubmitListener.beforeSubmit事件并将以下脚本添加到其中。请按照内联评论进行操作。

import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep
import com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep

//Please edit the header name as you wanted
def headerName = 'Authorization'


//a method which sets the headers
def setHttpHeaders(def headers) {
    def step = context.getProperty("wsdlRequest").testStep
    if (step instanceof RestTestRequestStep || step instanceof WsdlTestRequestStep) {
    def currentRequest = step.httpRequest
    def existingHeaders = currentRequest.requestHeaders
    headers.each {
           existingHeaders[it.key] = it.value
        }
        currentRequest.requestHeaders = existingHeaders
    } else {
      log.info 'not adding headers to the current step as it is not request type step'
    }
}

//read the token from project properties
def token = context.expand('${#Project#TOKEN}')
//assert the value of token
assert token, "Token is null or empty"

//UPDATE from the comment to add the header to next request
if (token) {
  def headerValue = [(token)]
  def headers = [(headerName) : (headerValue)]
  setHttpHeaders(headers)
}

答案 1 :(得分:0)

 import groovy.json.JsonSlurper
import groovy.json.*

def tokens=testRunner.runStepByname("Token")
def response = context.expand( '${Token#Response}' )
def JsonSlurperjsonSlurper = newJsonSlurper()
def Objectresult = jsonSlurper.parseText(response)
def access_token= result.access_token

def authorization = "Bearer "+access_token
testRunner.testCase.setPropertyValue("access_token", authorization)