Come for the products,
stay for the community

The Atlassian Community can help you and your team get more value out of Atlassian products and practices.

Atlassian Community about banner
4,295,647
Community Members
 
Community Events
165
Community Groups

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

Edited

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

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

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

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

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

Hi @Hamza,

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

Suggest an answer

Log in or Sign up to answer
TAGS
Community showcase
Published in Jira Software

Upcoming changes to epic fields in company-managed projects

👋 Hi there Jira Community! A few months ago we shared with you plans around renaming epics in your company-managed projects. As part of these changes, we highlighted upcoming changes to epics on...

14,474 views 37 44
Read article

Community Events

Connect with like-minded Atlassian users at free events near you!

Find an event

Connect with like-minded Atlassian users at free events near you!

Unfortunately there are no Community Events near you at the moment.

Host an event

You're one step closer to meeting fellow Atlassian users at your local event. Learn more about Community Events

Events near you