1

all

I am working on JIRA, i am sending the authentication request from saparate code and i am getting the response, later i need to fetch all issues from the JIRA than i am sending the request that time i am getting the 401 (Unauthorized) while i am sending the same username and password with gZip compression. my first request code is following where from i am getting the proper response as authenticated.

string urll = ConfigurationManager.AppSettings["globalUrlForLP"];
HttpWebRequest request;
WebResponse response;
String uri;
LpResponse lp_response;
uri = urll + url;
request = WebRequest.Create(uri) as HttpWebRequest;
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = verb;
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Headers.Set("Authorization", Convert.ToBase64String(Encoding.ASCII.GetBytes(this.Username + ":" + this._password)));

if (null != data)
{
    request.ContentType = "application/json";
    String jsonPayload = JsonConvert.SerializeObject(data);
    byte[] jsonPayloadByteArray = Encoding.ASCII.GetBytes(jsonPayload.ToCharArray());
    request.GetRequestStream().Write(jsonPayloadByteArray, 0, jsonPayloadByteArray.Length);
}
lp_response = new LpResponse();
try
{
     response = request.GetResponse();
     StreamReader reader = new StreamReader(response.GetResponseStream());
     lp_response.response = reader.ReadToEnd();
}
catch (Exception e)
{
     lp_response.error = e;
}
return lp_response;
}

from it i am getting response as following.

{
  "session": {
  "name": "JSESSIONID",
  "value": "12345678901234567890"
  },
    "loginInfo": {
    "failedLoginCount": 10,
    "loginCount": 127,
    "lastFailedLoginTime": "2014-10-28T06:52:52.211+0000",
    "previousLoginTime": "2014-10-28T06:52:52.211+0000"
     }
}

Now come to the point, I want to get all projects from the JIRA for that i written following code and i am getting here 401 Unathorized. After getting this i read the JIRA REST Api documentation and there i found following.

"Returns information about the caller's session if the caller is authenticated. Note that the response contains the Set-Cookie HTTP headers that must be honoured by the caller. If you are using a cookie-aware HTTP client then it will handle all Set-Cookie headers automatically. This is important because setting the JSESSIONID cookie alone may not be sufficient for the authentication to work."

so please suggest me what i need to do more with following code ?

my Failure code is following.

string url = ConfigurationManager.AppSettings["urlAllJiraProject"];
LpResponse res = new LpResponse();
HttpWebRequest request;
WebResponse response;
List<AllJiraProject> jiraproject = new List<AllJiraProject>();
request = WebRequest.Create(url) as HttpWebRequest;
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "GET";
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Headers.Set("Authorization", Convert.ToBase64String(Encoding.ASCII.GetBytes(userNamejira + ":" + passwordjira)));
LpResponse lp_response = new LpResponse();
try
{
    response = request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream());
    lp_response.response = reader.ReadToEnd();
    jiraproject = (List<AllJiraProject>)JsonConvert.DeserializeObject<List<AllJiraProject>>(lp_response.response.ToString());
}
catch (Exception e)
{
    lp_response.error = e;
}
return jiraproject;
Ashish-BeJovial
  • 1,829
  • 3
  • 38
  • 62

2 Answers2

1

The accepted answer uses basic authentication and not a cookie. When requesting the cookie you don't need add any authorization to the headers. This method will accept a json string with the user name and password and the URL. It will return the cookie values.

public async Task<JiraCookie> GetCookieAsync(string myJsonPass, string JiraCookieEndpointUrl)
        {
            using (var client = new HttpClient())
            {
                var response = await client.PostAsync(
                    JiraCookieEndpointUrl,
                     new StringContent(myJsonPass, Encoding.UTF8, "application/json"));

                var json = response.Content.ReadAsStringAsync().Result;
                var jiraCookie= JsonConvert.DeserializeObject<JiraCookie>(json);
                return jArr;
            }
        }

public class JiraCookie
    {
        public Session session { get; set; }
    }

public class Session
{
    public string name { get; set; }
    public string value { get; set; }
}

When I call it using url: http://[baseJiraUrl]/rest/auth/1/session it returns the following JSON response:

{
"session" : -{
"name" : JSESSIONID,
"value" : cookieValue
}

Keep in mind the URL above is valid in the version of JIRA I'm using and may vary depending on which version you're using.

Read the JIRA API documentation for the correct URL for the version you are using.

Check out this answer on how add cookies to your HttpClient request.

How do I set a cookie on HttpClient's HttpRequestMessage

ismael.
  • 418
  • 2
  • 7
0

I got it, my code does not have Basic authentication into the header, while API demands the Basic authentication, so i replaced my one line with following two lines.

Replaced line

request.Headers.Set("Authorization", Convert.ToBase64String(Encoding.ASCII.GetBytes(userNamejira + ":" + passwordjira)));

Replaced By

byte[] authBytes = Encoding.UTF8.GetBytes("user:password".ToCharArray()); 
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);

Jira has three type of authentications, this one from Basic authentication, it is easy to implement, but i had no idea how to implement authentication from cookie.

Ashish-BeJovial
  • 1,829
  • 3
  • 38
  • 62