How do I log in jira using REST api?

Giuseppe La Femina January 19, 2012

Hello all I'm using Jira 4.4.

I'm trying to make a plugin that performs some simple jql queryies via RESt.

In order to do so I need to log in Jira with my plug in.

How do I have to do?

I tried in two different way

1) Java Script

<form  method="POST">
    Username: <input type="text" name="username" /> <br />
    Password: <input type="password" name="password" /> <br />
    <input type="button" value="Check In" name="Submit" onclick=javascript:login(username.value,"username",password.value,"password") >
    </form>

    
</form>
    
  <script language = "javascript">
  
		function login(username, password) {
		var url = "http://172.16.1.24/jira/rest/auth/1/session";
		var JSONObject = {"username": ""+username+"", "password": ""+password+""};
		
		var client = new XMLHttpRequest();
		
		client.open("POST", url, false);
		client.setRequestHeader("Content-Type", "application/json");
		
		
		client.send(JSONObject);
		
		

		if (client.status == 200)
			   alert("The request succeeded!\n\nThe response representation was:\n\n" + client.responseText)
		else
			   alert("The request did not succeed!\n\nThe response status was: " + client.status + " " + client.statusText + ".");
			    
		}

    </script>

And a second one using Java (I'm using Play!Framework)

String wsReq = "{\"username\": \""+username+"\", \"password\": \""+password+"\"}";
		HttpResponse response = WS.url("http://172.16.1.24/jira/rest/auth/1/session").setHeader("Content-Type", "application/json").body(wsReq).post();

with the first one I don't get any answer from the server, with second one I'm authenticated but non session information are stored and I cant make any other request.

Somewhere I read that I have to use the session ID in order to make others api calls. But where I put it if, as an example, I point to the url myhost/jira/rest/api/2.0.alpha1/searches

3 answers

1 vote
John Burns
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
July 17, 2012

For java, using apache httpclient and json.org reference implementation of JSONObject, i have a jira client.

it has the following class variables:

private DefaultHttpClient httpClient;
private HttpHost targetHost;
private JiraSession session;

my login function looks like this:

try {
            HttpPost post = new HttpPost(config.getBaseUrl() + "rest/auth/latest/session");
            JSONObject reqContent = new JSONObject();
            reqContent.put("username", config.getUserName());
            reqContent.put("password", config.getPassword());
            StringEntity se = new StringEntity(reqContent.toString());
            se.setContentType("application/json");
            post.setEntity(se);
            ResponseHandler&lt;String&gt; responseHandler = new BasicResponseHandler();
            String responseBody = httpClient.execute(targetHost, post, responseHandler);
            JSONObject obj = new JSONObject(responseBody);
            session = new JiraSession();
            session.setName(obj.getJSONObject("session").getString("name"));
            session.setName(obj.getJSONObject("session").getString("value"));
            CookieStore cookieStore = new BasicCookieStore();
            BasicClientCookie cookie = new BasicClientCookie(obj.getJSONObject("session").getString("name"),
                                                             obj.getJSONObject("session").getString("value"));
            cookie.setDomain(targetHost.getHostName());
            cookie.setPath("/");
            cookieStore.addCookie(cookie);
            httpClient.setCookieStore(cookieStore);           
        } catch (ParseException | IOException ex) {
            Logger.getLogger(JiraClient.class.getName()).log(Level.SEVERE, null, ex);
        }

Then subsequest calls are made as such:

HttpGet get = new HttpGet(config.getBaseUrl() + "rest/api/latest/filter/favourite");
        ResponseHandler&lt;String&gt; responseHandler = new BasicResponseHandler();
        String responseBody = httpClient.execute(targetHost, get, responseHandler);

1 vote
rich
Atlassian Team
Atlassian Team members are employees working across the company in a wide variety of roles.
January 19, 2012

Another way (and better way) is to use OAuth. You can find examples here: https://bitbucket.org/atlassian_tutorial/atlassian-oauth-examples

Giuseppe La Femina January 22, 2012

Thank you Rich!

I'm giving it a look!

Like Revenue Manager likes this
zhang xu June 12, 2013

thank you Rich too!

MB
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
August 21, 2013

Could you please re-post the valid URL, since this one is broken :(

rich
Atlassian Team
Atlassian Team members are employees working across the company in a wide variety of roles.
August 21, 2013

@Mladen sure thing... I updated the URL above to https://bitbucket.org/atlassian_tutorial/atlassian-oauth-examples

jin turing May 20, 2018

Hi, with above oauth example(https://bitbucket.org/atlassian_tutorial/atlassian-oauth-examples), how can I get the token with login of different user?

actually I got error as follow.

oauth=WWW-Authenticate: OAuth realm="https://example.atlassian.net", oauth_problem="consumer_key_unknown".

I want to register only one of jira link application on my atlassian.net and to access other any atlassian.net via jira api.

1 vote
JamieA
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
January 19, 2012

If it's a jira plugin then you will use the user's session data, so logging in should not be necessary. Are you trying to log in as a different user? This is a bad ideas as the user's credentials will be plain view in the source.

Giuseppe La Femina January 19, 2012

I'm trying to use rest to develop a webapp i want to deploy in my company intranet. So, right now, I'm no so much concerned about security

JamieA
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
January 19, 2012

For the java one, you should get a JSESSIONID which you can pass as a header in subsequent requests. For javascript, if you are running the javascript in jira, I'm not sure, because the cookie set by the /auth might conflict with jira's auth token.

Try installing the rest browser too, eg: https://jira.atlassian.com/plugins/servlet/restbrowser#/com-atlassian-jira-rest-jira-rest-authentication-filter

Post data: {"username": "jechlin", "password": "******"}

Giuseppe La Femina January 22, 2012

Thank you Jamie, so for the Java one if i want to make a jql query with post my lines should be:

String jql = "{\"jql\": \"project = "+project+"\" , \"startAt\": 0, \"maxResults\": 15}";
	HttpResponse response = WS.url("http://172.16.1.24/jira/rest/api/2.0.alpha1/search").setHeader("Content-Type", "application/json", "JSESSIONID", jsessionid).body(jql).post();

Suggest an answer

Log in or Sign up to answer