Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

Next challenges

Recent achievements

  • Global
  • Personal

Recognition

  • Give kudos
  • Received
  • Given

Leaderboard

  • Global

Trophy case

Kudos (beta program)

Kudos logo

You've been invited into the Kudos (beta program) private group. Chat with others in the program, or give feedback to Atlassian.

View group

It's not the same without you

Join the community to find out what other Atlassian users are discussing, debating and creating.

Atlassian Community Hero Image Collage

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

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

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".

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.

 

 

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.

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

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. 

I will check that and update.

In JIRA advanced search, '=' is permitted.

4.png

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:.

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

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

TAGS
Community showcase
Published in Opsgenie

Opsgenie and Amazon team up to launch new DevOps Guru integration - now available!

We’re proud to announce that our integration with Amazon DevOps Guru is now live. The Amazon and Opsgenie product teams have worked together to build a deep integration between Opsgenie and the new...

280 views 0 11
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