Scriptrunner REST endpoint authentication Edited

Hello, I am trying to create REST endpoint to query JIRA REST API in the same instance of JIRA and I have some issues with authorization. While I can use basic authorization, I need to use current logged user context and get rid of hardcoded credentials in endpoint source code.

Here is my script based on some examples on adaptivist site:

import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovyx.net.http.HTTPBuilder
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpRequest;
import org.apache.http.protocol.HttpContext;
import groovy.json.JsonSlurper;
import groovy.json.JsonBuilder;
import groovyx.net.http.Method
import groovyx.net.http.ContentType
import groovy.transform.BaseScript
import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response
@BaseScript CustomEndpointDelegate delegate 

listProjects( 
    httpMethod: "GET") { MultivaluedMap queryParams -> 
def JIRA_REST_URL = "https://jira-test"
def JIRA_API_URL = JIRA_REST_URL + "/rest/api/2/project"
def httpBuilder = new HTTPBuilder(JIRA_API_URL);
httpBuilder.client.addRequestInterceptor(new HttpRequestInterceptor() {
void process(HttpRequest httpRequest, HttpContext httpContext) {
httpRequest.addHeader('Authorization', 'Basic ' + 'user:pass'.bytes.encodeBase64().toString())
}
})
def rt = [:]
def projects = httpBuilder.request(Method.GET, ContentType.JSON) {
            uri.path = "/rest/api/2/project"
            response.failure = { resp, reader ->
                 log.warn("Failed to query JIRA API: " + reader.text)
             }
        }
 
    rt = [
        items: projects.collect { project ->
            [
                   value: project.id,
                   html : project.key,
                   label: project.key,
            ]
        }
    ]
 

return Response.ok(new JsonBuilder(rt).toString()).build();
}

P.S. I am trying to get project list and issue type list and then use convertToSingleSelect() functionality, may be it is possible to do internally, without REST API calls.

 

 

 

1 answer

1 accepted

1 vote
Accepted answer

Hey Максим,

If I understand your request correctly, you would like a Custom REST Endpoint where only authenticated JIRA users can retrieve a list of project information.

I have written an example script that will achieve this using the ScriptRunner REST Endpoints. This example will give you a list of projects with their corresponding issue types.

import com.atlassian.jira.component.ComponentAccessor
import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.json.JsonBuilder
import groovy.transform.BaseScript

import javax.servlet.http.HttpServletRequest
import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response

@BaseScript CustomEndpointDelegate delegate

getProjects(httpMethod: "GET", groups: ["jira-users"]) { MultivaluedMap queryParams, String body, HttpServletRequest request ->
    // Get the projects
    def pm = ComponentAccessor.getProjectManager()
    def projects = pm.getProjects()

    def rt = [
        items: projects.collect { project ->
            [
                value     : project.id,
                html      : project.key,
                label     : project.key,
                issueTypes: project.getIssueTypes().collect { issueType ->
                    [
                        id  : issueType.id,
                        name: issueType.name
                    ]
                }
            ]
        }
    ]

    return Response.ok(new JsonBuilder(rt).toString()).build()
}


Enforcing Users

The way that this enforces users is that I have set the groups parameter to "jira-users" (line 12). This means that ONLY authenticated JIRA users who are in the jira-users group can access this resource.

You could also achieve this by getting the user and checking it yourself. An example of this approach is in the SR documentation. I would recommend the approach that I have demonstrated as it is more maintainable.

Getting a list of projects

As you suggested in your post, you can get the projects and issue type data without the need to make a call to another rest endpoint. The example I have given you demonstrates how to do this using the ProjectManager utility.

Hello, Stephen. Thank you for your answer. It was really like I had been trying to reinvent the wheel with my attempts to use JIRA REST. Your solution is exactly what I need.

 

P.S. I also have found solution for my auth problem : I've forwarded Cookie header from initial endpoint request to JIRA REST.

Hi Максим,

How did you forwarded the Cookie? I ran into the same problem as you - I want to use HTTPBuilder but as a currently logged in user but by default all requests are being sent as anonymous.

Regards,

Bartek

Suggest an answer

Log in or Sign up to answer
Community showcase
Published Nov 29, 2018 in Marketplace Apps

How to set up an incident workflow from the VP of Engineering at Sentry

Hey Atlassian community, I help lead engineering at Sentry, an open-source error-tracking and monitoring tool that integrates with Jira. We started using Jira Software Cloud internally last year, a...

1,290 views 0 8
Read article

Atlassian User Groups

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

Find a group

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

Find my local user group

Unfortunately there are no AUG chapters near you at the moment.

Start an AUG

You're one step closer to meeting fellow Atlassian users at your local meet up. Learn more about AUGs

Groups near you