I am trying to use the Active Choices Plugin to create a dynamic dropdown that lists projects from an external tool (e.g., JFrog/SonarQube) by calling its REST API.
Problem: > I am struggling to securely retrieve a Secret Text credential within the Groovy script and use it in an Authorization header. I am running into two main issues:
-
Sandbox Violations: My script is being blocked by the Groovy Sandbox (errors like RejectedAccessException).
-
Context Access: I am unsure of the safest way to lookup credentials without using the high-privilege Jenkins.instance.
What I’ve tried:
-
I used CredentialsProvider.lookupCredentials, but it requires multiple admin approvals in “In-Process Script Approval.”
-
I tried running without the Sandbox, but I want to follow security best practices.
Request: Could someone provide a “Best Practice” code snippet for an Active Choices script that:
Hi,
I have done something similar in the past and I have used the CredentialsProvider.lookupCredentials method you are suggesting. I was running it without the Sandbox.
This was the script:
import com.cloudbees.plugins.credentials.CredentialsProvider
import com.cloudbees.plugins.credentials.Credentials
import groovy.json.JsonSlurper
def credentials = CredentialsProvider.lookupCredentials(Credentials.class).findResult { it.id == “my-credentials” ? it : null }
def req = new URL(“https://my-api.com/my-resource”).openConnection()
def userCredentials = credentials.username + “:” + credentials.password
def basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()))
req.setRequestProperty (“Authorization”, basicAuth)
def jsonSlurper = new JsonSlurper()
def body = jsonSlurper.parseText(req.getInputStream().getText())
I know you were asking for something different but this is what I came up with when I needed it. Maybe you can partially use it. Let me know if you find a better way.
Thanks,
Giovanni