JIRA Rest API Login using C#

user1585432 picture user1585432 · Aug 8, 2012 · Viewed 31.2k times · Source

I've written below C# code to login to JIRA Rest API:

var url = new Uri("http://localhost:8090/rest/auth/latest/session?os_username=tempusername&os_password=temppwd");
var request = WebRequest.Create(url) as HttpWebRequest;
if (null == request)
{
 return "";
}
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = 200;
request.KeepAlive = false;
using (var response = request.GetResponse() as HttpWebResponse)
{
}

When I execute this, application just goes on running without returning any response. Please suggest if this is the right way of calling JIRA Login using REST API

Answer

Maffelu picture Maffelu · Aug 25, 2012

For basic authentication you need to send in the username and password in a base64-encoding. Guidelines can be found in the API examples on atlassians developer page: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Basic+Authentication , if you are doing it in C# you need to send the encoded data in the header in the following format:

"Authorization: Basic [ENCODED CREDENTIALS]"

Here is a simple example:

public enum JiraResource
{
    project
}

protected string RunQuery(
    JiraResource resource, 
    string argument = null, 
    string data = null,
    string method = "GET")
{
    string url = string.Format("{0}{1}/", m_BaseUrl, resource.ToString());

    if (argument != null)
    {
        url = string.Format("{0}{1}/", url, argument);
    }

    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    request.ContentType = "application/json";
    request.Method = method;

    if (data != null)
    {
        using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
        {
            writer.Write(data);
        }
    }

    string base64Credentials = GetEncodedCredentials();
    request.Headers.Add("Authorization", "Basic " + base64Credentials);

    HttpWebResponse response = request.GetResponse() as HttpWebResponse;

    string result = string.Empty;
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        result = reader.ReadToEnd();
    }

    return result;
}

private string GetEncodedCredentials()
{
    string mergedCredentials = string.Format("{0}:{1}", m_Username, m_Password);
    byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
    return Convert.ToBase64String(byteCredentials);
}

(JiraResource is just an enum I use to decide which part of the API to use)

I hope this will help!