使用C#JIRA的REST API登录(JIRA Rest API Login using C#)

2019-06-26 21:26发布

我已经写了下面的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登录的正确方法

Answer 1:

对于基本身份验证您需要用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的一部分)

我希望这个能帮上忙!



Answer 2:

这里是一个其工作方式需要简单的解决方案:

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


Answer 3:

如果你不想在编码每个请求您的凭据这里是如何使用Cookie来做到这一点。

当请求的cookie,你不需要添加报头来任何授权。 此方法将接受一个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] /休息/ AUTH / 1 /会话它返回下列JSON响应:

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

请记住上面的网址是JIRA的版本,我使用的是有效的,并且可根据您所使用的版本有所不同。 阅读您正在使用的版本是正确的网址JIRA API文档。 我使用的是以下情况: https://docs.atlassian.com/software/jira/docs/api/REST/7.6.1/#auth/1/session

请记住,你必须保存你的cookie,并用它在每个后续请求。 看看如何Cookie添加到您的HttpClient的请求,这样的回答: 我如何设置的HttpClient的HttpRequestMessage一个cookie 。

一旦你与cookie(注销)进行简单的发送与相同的URL后删除HTTP请求。



Answer 4:

我调整了RunQuery代码,以便它今天会(4月2018)。 下面所引用的加密/解密方法是从下面的链接(I它转换为一个扩展方法和投掷值到环境)。

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

我成功地执行从代码LinqPad RunQuery后从而转储()命令-

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;
    }
}


Answer 5:

对于休息张贴多的内容我用Tiny.RestClient 。

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

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


文章来源: JIRA Rest API Login using C#
标签: c# rest jira