REST API authentication and how to pass JSESSIONID in subsequent request with JQuery/ MVC?

Mahi October 26, 2016

I am passing able to authenticate with REST API from MVC Controller and able to get JSESSIONID.

I was tried to pass the cookie in header for the next requests, but it was throwing error like

The field 'worklogAuthor' can't be found or ananymous users can't access it.

Can some one help in how to pass the header in the next requests...?

 

below is my code:

 

$(document).ready(function () {


url = '@Url.Action("Authenticate", "Home")';
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
success: function (data) {

var result = jQuery.parseJSON(data);
console.log(data);
JIRASessionId = result.session;
},
error: function (msg) {
debugger;
alert("Error:" + msg.responseText);
}
});
});

///Action Method
public JsonResult Authenticate()
{
var data = AuthenticateJIRAApi();
return Json(data, JsonRequestBehavior.AllowGet);
}

 

public string AuthenticateJIRAApi()
{
try
{
string baseUrl = "https://mysiteTest.atlassian.net";

 

String url = baseUrl + "/rest/auth/1/session";
string username = "xxxxxxxxx";
string password = "xxxxxxxxxx";

LoginInfo obj = new LoginInfo();
obj.username = username;

obj.password = password;

 

var parameters = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

 

var req = WebRequest.Create(url);

req.Method = "POST";
req.ContentType = "application/json";

byte[] bytes = Encoding.ASCII.GetBytes(parameters);

req.ContentLength = bytes.Length;

using (var os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);

os.Close();
}
HttpWebResponse webresponse = req.GetResponse() as HttpWebResponse;

var stream = webresponse.GetResponseStream();

if (stream != null)
using (stream)
using (var sr = new StreamReader(stream))
{
var result = sr.ReadToEnd().Trim();

return result;
}

}
catch (Exception ex)
{
}
return "";
}

 I was able to get the JSESSIONID and pass it with ajax request.


function setHeader(xhr) {
debugger;
xhr.setRequestHeader('cookie', JIRASessionId.name + '=' + JIRASessionId.value);
}

// Next Call to API.

$.ajax({
type: "GET",
url: api,
dataType: "json",
contentType: "application/json",
//headers: {
// // Set the cookie from the session information
// cookie: sess.name + '=' + sess.value
//},
//async: false,
beforeSend: setHeader,
success: function (data) {
},
error: function (errormessage) {
debugger;
alert("Error:" + errormessage.responseText);
console.log("errorMessage:", errormessage);
}
});

 

 

Even i tried calling the api from controller also, which results same error.

 

var req = WebRequest.Create(url);

req.Method = "GET";
req.ContentType = "application/json";

//Adding cookie in header like below .

req.Headers.Add("cookie", sessionName+"="+ sessionId);

 

HttpWebResponse webresponse = req.GetResponse() as HttpWebResponse;

var stream = webresponse.GetResponseStream();

 

 

 

Thanks in advance..

1 answer

Comments for this post are closed

Community moderators have prevented the ability to post new answers.

Post a new question

0 votes
Volodymyr Krupach
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.
October 26, 2016

I see that you do everything as in Cookie-based example and as per me it should work. To clarify the matter try debugging your calls. Make sure that JSESSIONID cookie header is sent.

You did not mention what method you call but as per error I guess that you try to add worklogs. Please be aware that worklogs can be added only under currently authenticated used. You will not be able to put worklog for user B being authenticated as user A by passing worklogAuthor: "B".

Mahi October 26, 2016

I am using JQL query to fetch the issues for which particular user logged hours.

string url = "https://mysite.atlassian.net/rest/api/2/search?startIndex=0&jql=worklogAuthor = '" + myUserName +" ' ";

 

  In MVC Controller  - using WebRequest:

string worklogAuthor = "XXXXXXX";

   string url = string.Format("https://mysite.atlassian.net/rest/api/2/search?startIndex=0&jql=(worklogAuthor={0})", worklogAuthor);
                            
                var req = WebRequest.Create(url);

                req.Method = "GET";
                req.ContentType = "application/json";               
               
                req.Headers.Add("cookie", sessionName+ "="+ sessionValue );
                

                HttpWebResponse webresponse = req.GetResponse() as HttpWebResponse;
              
                var stream = webresponse.GetResponseStream();

                if (stream != null)
                    using (stream)
                    using (var sr = new StreamReader(stream))
                    {
                        var result = sr.ReadToEnd().Trim();
                        //return JsonConvert.DeserializeObject(result);//Return result
                        return Json(result, JsonRequestBehavior.AllowGet);
                    }


Returning exception with error message

  "The remote server returned an error: (400) Bad Request. "

    and also sometimes

"The remote server returned an error: (401) Unauthorized."

 

1.png

Kindly help.

 

 

Volodymyr Krupach
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.
October 26, 2016

Try running search with empty JQL param:

rest/api/latest/search?jql=

If it's run fine then you have some problems with jql. Test it on JIRA, Search for Issues page. Maybe you need to escape "=" that goes after worklogAuthor but I never did any nodejs so it just a guess.

Mahi October 26, 2016

With empty JQL it is fetching data.

2.png

If we use like below

string url = "https://test.atlassian.net/rest/api/latest/search?jql=worklogAuthor=" + worklogAuthor ;     

throwing exception.

even tried in browser, its working.

3.png

Volodymyr Krupach
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.
October 26, 2016

please see me previous comment:
> Maybe you need to escape "=" that goes after worklogAuthor but I never did any nodejs so it just a guess. 

Mahi October 26, 2016

I will check that and update.

In JIRA advanced search, '=' is permitted.

4.png

Volodymyr Krupach
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.
October 26, 2016

sure, it's permitted smile.
I think that the problem is in your nodejs code were you form the URL:

string.Format("https://mysite.atlassian.net/rest/api/2/search?startIndex=0&jql=(worklogAuthor={0})", worklogAuthor);

My guess is that you need:

  • remove "(" and ")" brackets
  • maybe escape "=" that goes after worklogAuthor. Try to replace it with encoded representation whtich is "%3D"

I do no have any nodejs expirience so you have to figure it on your own smile.

Mahi October 27, 2016

Even though i pass encoded string, it throwing same error.

https://mysite.atlassian.net/rest/api/latest/search?jql=worklogAuthor%3DMyUserName"

TAGS
AUG Leaders

Atlassian Community Events