使用C#进行JIRA Rest API登录

时间:2012-08-08 17:17:36

标签: c# rest jira

我在下面写了C#代码来登录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)
{
}

当我执行此操作时,应用程序继续运行而不返回任何响应。请建议这是否是使用REST API调用JIRA登录的正确方法

6 个答案:

答案 0 :(得分:34)

对于基本身份验证,您需要使用base64编码发送用户名和密码。可以在atlassians开发者页面的API示例中找到指南: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Basic+Authentication ,如果你在C#中这样做,你需要按照以下格式在标题中发送编码数据:

“授权:基本[编码证书]”

这是一个简单的例子:

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只是我用来决定使用哪个API部分的枚举)

我希望这会有所帮助!

答案 1 :(得分:4)

这是一个更简单的解决方案,可以按要求运行:

var mergedCredentials = string.Format("{0}:{1}", username, password);
var byteCredentials = Encoding.UTF8.GetBytes(mergedCredentials);
var encodedCredentials = Convert.ToBase64String(byteCredentials);

using (WebClient webClient = new WebClient())
{
    webClient.Headers.Set("Authorization", "Basic " + encodedCredentials);

    return webClient.DownloadString(url);
}

答案 2 :(得分:2)

如果您不想在每个请求中对您的凭据进行编码,请参阅使用Cookie。

请求Cookie时,您不需要在标头上添加任何授权。此方法将接受带有用户名和密码以及URL的JSON字符串。它将返回cookie值。

public async Task<JiraCookie> GetCookieAsync(string myJsonUserNamePassword, string JiraCookieEndpointUrl)
{
    using (var client = new HttpClient())
        {
            var response = await client.PostAsync(
                JiraCookieEndpointUrl,
                new StringContent(myJsonUserNamePassword, 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; }
}

当我使用url:http://[baseJiraUrl]/rest/auth/1/session调用它时,它会返回以下JSON响应:

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

请注意,上述网址在我使用的JIRA版本中有效,并且可能会因您使用的版本而异。阅读JIRA API文档,了解您使用的版本的正确URL。我使用以下内容: https://docs.atlassian.com/software/jira/docs/api/REST/7.6.1/#auth/1/session

请记住,您必须存储您的Cookie并在每个后续请求中使用它。 查看有关如何在您的HttpClient请求中添加Cookie的答案:How do I set a cookie on HttpClient's HttpRequestMessage

完成cookie后(注销)只需发送一个删除http请求,其URL与帖子相同。

答案 3 :(得分:0)

我调整了RunQuery代码,以便它今天运行(2018年4月)。下面引用的加密/解密来自以下链接(我将其转换为扩展方法并将值投入环境)。

https://stackoverflow.com/questions/10168240/encrypting-decrypting-a-string-in-c-sharp

我成功执行了LinqPad中的代码 - 因此在RunQuery

之后执行了Dump()命令
private string _baseUrl = "https://xxxxxx.atlassian.net";
private string _username = "YourLogin";

void Main()
{
    RunQuery(JiraResource.project).JsonToXml().Dump();
}

public enum JiraResource { project }

private const string restApiVersion = "/rest/api/2/";

protected string RunQuery(  JiraResource resource,  string argument = null, string data = null, string method = "GET")
{
    string url = $"{_baseUrl}{restApiVersion}{resource}";

    if (argument != null) url = $"{url}{argument}/";

    var 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);

    var response = request.GetResponse() as HttpWebResponse;
    string result = string.Empty;
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        result = reader.ReadToEnd();
    }
    return result;
}

private string GetEncodedCredentials()
{
    var encryptedPassword = Environment.GetEnvironmentVariable("PassEncrypted");
    var encryptionSalt = Environment.GetEnvironmentVariable("PassSalt");
    var password = encryptedPassword.Decrypt(encryptionSalt);

    var mergedCredentials = $"{_username}:{password}";
    var byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
    return Convert.ToBase64String(byteCredentials);
}

public static class MyExtensions
{
    public static XElement JsonToXml(this string jsonData, bool isAddingHeader = true)
    {
        var data = isAddingHeader
            ? "{\"record\":" + jsonData + "}"
            : jsonData;

        data = data // Complains if xml element name starts numeric
            .Replace("16x16", "n16x16")
            .Replace("24x24", "n24x24")
            .Replace("32x32", "n32x32")
            .Replace("48x48", "n48x48");

        var result = JsonConvert.DeserializeXmlNode(data, "data");
        var xmlResult = XElement.Parse(result.OuterXml);
        return xmlResult;
    }
}

答案 4 :(得分:0)

要在Rest中发布多部分内容,我使用Tiny.RestClient

var client = new TinyRestClient(new HttpClient(), "http://localhost:8090");

var strResult = await client.PostRequest("rest/auth/latest/session).
WithBasicAuthentication("username", "password")
ExecuteAsStringAsync();

答案 5 :(得分:0)

static void Main(string[] args)
{
    using (WebClient wc = new WebClient())
    {
        wc.Headers.Add("Authorization", "Basic " + GetEncodedCredentials());

        string tasks = wc.DownloadString("yourjiraurl/search?jql=task=bug");
        var taskdetails = JsonConvert.DeserializeObject<TaskDetails>(tasks);
    }
}

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