Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

Make REST API call as logged user with scriptrunner without hardcoded credentials

Rafał Nowakowski
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
April 22, 2020

Hello,

I am using Behaviour Select List Conversions which is described here https://scriptrunner.adaptavist.com/4.3.5/jira/behaviours-conversions.html.

I want to make a field that will allow me to select Test Cycle in Test Plan (SynapseRT Plugin). To ask about those cycles I can use SynapseRT REST API "Get Test Cycles in a Test Plan" (GET /rest/synapse/latest/public/testPlan/{testPlanIssueKey}/cycles).

Thus I need to make external api call which in fact is internal because baseURL and credentials I need to provide are the same like in Jira.

Currently in my Rest-Endpoint code I am using basicAuth:

def url = new URL("$jiraBaseUrl/rest/synapse/latest/public/testPlan/$planKey/cycles")

def urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", jiraCredentials)
urlConnection.connect()

Is there any way to get rid of hard-coded credentials?

I have also some rest-endpoints which connects with bamboo and I see possibilities to do calls as logged in user... so i belive that there is also possiblitiy to do sth similar wtih Jira - Jira like in Jira - Bamboo.

In Jira-Bamboo Rest-Endpoint i do requests with such auth:

// Integration & Auth Info
def techUser = ComponentAccessor.jiraAuthenticationContext.setLoggedInUser(ComponentAccessor.getUserManager().getUserByName("jira-test-user"))
def appLinkService = ComponentLocator.getComponent(ApplicationLinkService)
def appLink = appLinkService.applicationLinks.findAll{it -> it.name.toString()=="BambooPRE"}
ApplicationLink bambooAppLink = appLink?.getAt(0)
def applicationLinkRequestFactory = bambooAppLink.createAuthenticatedRequestFactory()

 

 

 

 

1 answer

0 votes
Andreas October 2, 2020

Hi Rafal!

Have you found a solution for this? I am also using REST calls from Jira to Confluence through the applink without hardcoded credentials but I need a REST call from Jira to itself....

Best regards
Andreas

Hamza July 30, 2021

Hi @Andreas,

can you tell me how you are using REST calls from Jira to Confluence through the applink without hardcoded credentials? I didn't find a way yet and I would need it to make a REST call from Jira to Bitbucket (with the currently logged-in User).

Kind regards,

Hamza

Andreas August 2, 2021

Hi @Hamza 

I use the script like this:

def jiraAuthenticationContext = ComponentAccessor.getJiraAuthenticationContext()
def userManager = ComponentAccessor.getUserManager()
def currentUser = jiraAuthenticationContext.getLoggedInUser()
def adminUser = userManager.getUserByName("admin123")

//jiraAuthenticationContext.setLoggedInUser(adminUser)

def confluenceLink = getPrimaryConfluenceLink()
def authenticatedRequestFactory = confluenceLink.createImpersonatingAuthenticatedRequestFactory()

// Copy Space
authenticatedRequestFactory
.createRequest(Request.MethodType.POST, "/rest/scriptrunner/latest/canned/com.onresolve.scriptrunner.canned.confluence.admin.CopySpace")
.setSoTimeout(30000)
.addHeader("Content-Type", "application/json")
.setRequestBody(input)
.execute(new ResponseHandler<Response>() {
@Override
void handle(Response response) throws ResponseException {
if(response.statusCode != HttpURLConnection.HTTP_OK) {
throw new Exception(response.getResponseBodyAsString())
}
else {
def webUrl = new JsonSlurper().parseText(response.responseBodyAsString)
}
}
}
)

def ApplicationLink getPrimaryConfluenceLink() {
def applicationLinkService = ComponentLocator.getComponent(ApplicationLinkService.class)
final ApplicationLink conflLink = applicationLinkService.getPrimaryApplicationLink(ConfluenceApplicationType.class)
conflLink
}

The current user is set in the jiraAuthenticationContext. This is also the user who executes the REST request. 

I have also a scenario where I have to set the logged in user to an admin user (this line is commented)

Best regards

Andreas

siteadmin August 9, 2021

.

Hamza August 9, 2021

Hi @Andreas  ,

thanks for your answer.
I'm still not getting how to replace the authentication to use the current user.
Heres my code to generate a Pull request from Jira Datacenter to a linked Bitbucket Datacenter. 

//User
def authString = username + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);

// API POST Create Pull Request
def baseBitbucketURL = "{Bitbucket-URL}"
url2 = new java.net.URL(baseBitbucketURL);
try {
URLConnection connection = url2.openConnection();
connection.setRequestProperty("Authorization", "Basic "+ authStringEnc);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Content-Type", "application/json")
connection.setDoOutput(true);
connection.outputStream.withWriter("UTF-8") { new StreamingJsonBuilder(it, jsonBody1) }
connection.connect();
inputStream =  connection.getInputStream().getText()
result = slurper.parseText(inputStream)
log.info ("URL="+url+"Status="+connection.getResponseCode() as String)
}
catch(Exception e)
{  log.error("Fehler: " + e.toString())}

 

Can you tell me how I could replace the hard coded Username and password in this case?

Kind regards,

Hamza

Prateek Nigam
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
April 21, 2022

Hi @Hamza,

Are you able to call REST api without using hardcoded basic credential.

Suggest an answer

Log in or Sign up to answer