Last updated Mar 22, 2024

Cookie-based authentication

This page shows you how to allow REST clients to authenticate themselves using cookies. This is one of three methods that you can use for authentication against the Jira REST API; the other two are Basic authentication and OAuth.

The preferred authentication method for the Jira REST APIs is OAuth. Jira itself uses cookie-based authentication in the browser, so you can call REST from JavaScript on the page and rely on the authentication that the browser has established. To reproduce the behavior of the Jira login page (for example, to display authentication error messages to users), you can POST to the /auth/1/session resource.

Overview

Jira's REST API is protected by the same restrictions that are provided via Jira standard web interface. This means that if you do not log in, you access Jira anonymously. Furthermore, if you log in and do not have permission to view something in Jira, you will not be able to view it using the Jira REST API either.

In most cases, the first step in using the Jira REST API is to authenticate a user account with your Jira site. Any authentication that works against Jira will work against the REST API. In this tutorial, you will use cookie-based (session) authentication.

This is how cookie-based authentication works in Jira at a high level:

  1. The client creates a new session for the user via the Jira REST API .
  2. Jira returns a session object that has information about the session including the session cookie. The client stores this session object.
  3. The client can now set the cookie in the header for all subsequent requests to the Jira REST API. 

Before you begin, notice that although cookie-based authentication has many benefits, such as performance (not having to make multiple authentication calls), it also has security risks. For example, your session cookies can be hijacked if handled improperly. This page does not go into the security implications of cookies, but you should make yourself aware of the risks before considering this approach.

Before you begin

To complete this tutorial, you need to know the following: 

  1. The basics of using REST APIs, for example, requests, responses, headers, and so on.
  2. The basics of using and administering Jira.

Step 1. Create a new session using the Jira REST API

In this step, to get a session cookie from Jira, you will need to create a new session using the  session resource in the Jira REST API. 

Tip: You can also use the session resource to get information about the currently authenticated user in the current session (GET), or log the current user out of Jira (DELETE).

  1. To create a new session, POST the desired user credentials (as JSON) to the session resource:
1
2
curl -X POST \
  http://jira.example.com:8090/jira/rest/auth/1/session \
  -H 'content-type: application/json' \
  -d '{ "username": "myuser", "password": "mypassword" }'

This will create a new session and return the requested session information that will look similar to the following:

1
2
{
   "loginInfo" : {
      "lastFailedLoginTime" : "2013-11-27T09:43:28.839+0000",
      "previousLoginTime" : "2013-12-04T07:54:59.824+0000",
      "loginCount" : 2,
      "failedLoginCount" : 1
   },
   "session" : {
      "name" : "JSESSIONID",
      "value" : "6E3487971234567896704A9EB4AE501F"
   }
}

More importantly, you will get the session cookie (in the header of the response) from the server, which you can use in subsequent requests. You can see an example of this below. You'll notice that the cookie name and value are the same as the cookie name and value in the session response above.

1
2
Set-Cookie: JSESSIONID=6E3487971234567896704A9EB4AE501F; Path=/; HttpOnly

Now that you've created a session, it's just a matter of setting the cookie in all subsequent requests to the server. In this step, you do just that.

  1. Store the session object on the client. The way that you do this depends on how your client is implemented.

  2. When you want to make a request, take cookie name and value from the session and use them to set the cookie field in the header of your request. Here is an example:

    1
    2
    headers: {cookie: JSESSIONID=6E3487971234567896704A9EB4AE501F}
    

    Here is a curl example:

    1
    2
    curl -vv -b "JSESSIONID=2B63FEDB7629B24BD3FFECB5A547EF7D;" http://jira.example.com:8090/jira/rest/api/2/issue/TEST-3
    

That's it! Now, when you submit the request, the session cookie will be used to authenticate you to the Jira server until the cookie expires.

Example code (Node.js)

The following example is written for Node.js. It demonstrates how you get the session information from Jira, set the cookie using the session information, and then execute a request (in this case, a request for search results) with the cookie.

1
2
var Client = require('node-rest-client').Client;
client = new Client();
// Provide user credentials, which will be used to log in to JIRA.
var loginArgs = {
    data: {
        "username": "admin",
        "password": "admin"
    },
    headers: {
        "Content-Type": "application/json"
    }
};

client.post("http://localhost:8090/jira/rest/auth/1/session", loginArgs, function(data, response){
    if (response.statusCode == 200) {
        console.log('succesfully logged in, session:', data.session);
        var session = data.session;
        // Get the session information and store it in a cookie in the header
        var searchArgs = {
            headers: {
                // Set the cookie from the session information
                cookie: session.name + '=' + session.value,
                "Content-Type": "application/json"
            },
            data: {
                // Provide additional data for the JIRA search. You can modify the JQL to search for whatever you want.
                jql: "type=Bug AND status=Closed"
            }
        };
        // Make the request return the search results, passing the header information including the cookie.
        client.post("http://localhost:8090/jira/rest/api/2/search", searchArgs, function(searchResult, response) {
            console.log('status code:', response.statusCode);
            console.log('search result:', searchResult);
        });
    } else {
        throw "Login failed :(";
    }
});

Advanced topics

One disadvantage of using cookies compared to basic authorization is that they expire. You have probably noticed this when accessing Jira through a web browser. Every once in a while, especially if you have not used Jira in a while, you need to log in again because your cookie has expired. The same occurs when using REST. If you write a script or code that involves REST API calls and:

  • It only runs for a few minutes, then you should not worry about cookies expiring.
  • It runs for a longer period of time due to more complex integration activities, then expiring cookies may cause problems.

If you use REST with a cookie that has expired, you will receive a 401 error response from Jira. The response body will contain a message telling you that your cookie is invalid. At that point, you will need to re-authenticate to the session resource on the "auth" API.

To learn more, check the REST and os_authType page.

CAPTCHAs

CAPTCHA upon login is "triggered" after several consecutive failed login attempts, after which the user is required to interpret a distorted picture of a word and type that word into a text field with each subsequent login attempt.

Keep in mind that, once Jira's CAPTCHA upon login feature has been triggered, you cannot use Jira's REST API to authenticate with a Jira site.

When you get an error response from Jira, you can check for the presence of an X-Seraph-LoginReason header in the response, which will contain more information. A value of AUTHENTICATION\_DENIED or AUTHENTICATED\_FAILED  means the application rejected the login without even checking the password, which most commonly indicates that Jira's CAPTCHA feature has been triggered.

Form token checking

Jira employs a token authentication mechanism that is used whenever Jira actions are performed either through link request or form submission. This provides Jira with the means to validate the origin and intent of the request, thus adding an additional level of security against cross-site request forgery.

This affects any REST endpoints that use form encoding, for example, /issue/{issueIdOrKey}/attachments. If you need to use REST endpoints like these and you don't use basic authentication, you will need to disable the form token checking in your request. This is done by adding the appropriate header in your request. For details, see  the page about Form token handling.

Rate this page: