You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SoapUI脚本开头自动获取OAuth2访问令牌,无需点击「获取令牌」

Hey there! I’ve tackled this exact problem plenty of times—here’s how to automate OAuth2 token retrieval in SoapUI so you never have to click that "Get Token" button manually again. Let’s break it down into actionable steps:

The most reliable way is to add a Groovy script at the start of your test case that fetches the token and stores it for reuse.

  • First, add a Groovy Script test step as the very first item in your test case (before any request that needs the token).
  • Paste this script, then replace the placeholder values with your actual OAuth2 details:
import com.eviware.soapui.support.types.StringToStringMap
import com.eviware.soapui.impl.wsdl.support.http.HttpClientSupport
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.util.EntityUtils

// Replace these with your real OAuth2 configuration
def tokenEndpoint = "https://your-auth-server.com/oauth2/token"
def clientId = "your-client-id"
def clientSecret = "your-client-secret"
def grantType = "client_credentials" // Adjust to password/authorization_code if needed
def scope = "your-required-scopes"

// Build and send the token request
def postRequest = new HttpPost(tokenEndpoint)
def httpClient = HttpClientSupport.getHttpClient()

// Set required headers
postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded")

// Construct the request body
def requestBody = "client_id=${clientId}&client_secret=${clientSecret}&grant_type=${grantType}&scope=${scope}"
postRequest.setEntity(new StringEntity(requestBody))

// Execute request and parse response
def response = httpClient.execute(postRequest)
def responseBody = EntityUtils.toString(response.getEntity())
def tokenJson = new groovy.json.JsonSlurper().parseText(responseBody)

// Store token in a project-level property (reusable across all test cases)
context.testCase.testSuite.project.setPropertyValue("ACCESS_TOKEN", tokenJson.access_token)

// Optional: Log the token for debugging
log.info "Successfully fetched OAuth2 token: ${tokenJson.access_token}"
  • This script sends a direct POST request to your auth server, parses the JSON response, and saves the access_token to a project property. You can use test case/test suite properties instead if you don’t need the token across the entire project.

Once the token is stored, configure your API requests to use it automatically:

  • Open any request that needs OAuth2 authorization.
  • Go to the Authorization tab.
  • Select OAuth 2.0 as the authorization type.
  • In the "Access Token" dropdown, choose "From Property".
  • Pick the ACCESS_TOKEN property you created earlier from the list.
3. Alternative: Use SoapUI Pro’s Built-in OAuth2 Tools

If you’re using SoapUI Pro, you can leverage the pre-built OAuth2 API to avoid writing raw HTTP requests:

import com.eviware.soapui.security.oauth.OAuth2TokenGenerator
import com.eviware.soapui.model.security.OAuth2Profile

// Fetch your pre-configured OAuth2 profile (create this in Project > Security > OAuth2 Profiles first)
def oAuthProfile = context.testCase.testSuite.project.getOAuth2ProfileByName("YourOAuth2Profile")

// Generate token automatically using the profile settings
def tokenGenerator = new OAuth2TokenGenerator(oAuthProfile)
def token = tokenGenerator.generateToken()

// Save token to a property
context.testCase.testSuite.project.setPropertyValue("ACCESS_TOKEN", token.getAccessToken())
log.info "Auto-generated token via SoapUI Pro: ${token.getAccessToken()}"
  • This uses your pre-configured profile (with credentials and endpoint already set) so you don’t have to hardcode sensitive data in scripts.
4. Quick Troubleshooting Tips
  • Check the Logs: If the token fails to fetch, look at the SoapUI log panel (bottom of the window) for errors—common issues include typos in the endpoint, invalid credentials, or missing scopes.
  • Handle Token Expiry: Add a check in the script to verify if the existing token is still valid (use tokenJson.expires_in from the response) before fetching a new one to reduce unnecessary requests.
  • SSL Issues: If your auth server uses a self-signed certificate, enable relaxed SSL checking in SoapUI (File > Preferences > SSL > Enable relaxed SSL checking).

内容的提问来源于stack exchange,提问作者Badr Eddine Laaroussi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:09:47