使用 C# 的 JIRA Rest API 登录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11869780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:35:18  来源:igfitidea点击:

JIRA Rest API Login using C#

c#restjira

提问by user1585432

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

我写了下面的 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)
{
}

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

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

回答by Maffelu

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:

对于基本身份验证,您需要以 base64 编码发送用户名和密码。可以在 atlassians 开发人员页面上的 API 示例中找到指南:https: //developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Basic+Authentication,如果您在 C# 中执行此操作,则需要按以下格式发送标头中的编码数据:

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

(JiraResource 只是我用来决定使用 API 的哪一部分的枚举)

I hope this will help!

我希望这个能帮上忙!

回答by Rob King

Here is a simpler solution which works as required:

这是一个更简单的解决方案,可以根据需要工作:

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

回答by ismael.

If you don't want to encode your credentials in every request here is how to do it using cookies.

如果您不想在每个请求中对您的凭据进行编码,这里是如何使用 cookie 进行编码。

When requesting the cookie you don't need to add any authorization on the headers. This method will accept a JSON string with the user name and password and the URL. It will return the cookie values.

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

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

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

{
"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. I'm using the following: https://docs.atlassian.com/software/jira/docs/api/REST/7.6.1/#auth/1/session

请记住,上面的 URL 在我使用的 JIRA 版本中有效,并且可能因您使用的版本而异。阅读 JIRA API 文档以获取您正在使用的版本的正确 URL。我正在使用以下内容:https: //docs.atlassian.com/software/jira/docs/api/REST/7.6.1/#auth/1/session

Remember you'll have to store your cookie and use it on every subsequent request. Check out this answer on how add cookies to your HttpClient request: How do I set a cookie on HttpClient's HttpRequestMessage.

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

Once you're done with the cookie (logging out) simply send a delete http request with the same URL as the post.

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

回答by BillKrat

I tweaked the RunQuery code so that it will run today (Apr 2018). The encrypt/decrypt referenced below is from the following link (I converted it to an extension method and threw values into environment).

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

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

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

I successfully execute the code from LinqPad- thus the Dump() command after RunQuery

我成功地从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;
    }
}

回答by user8803505

For posting multipart content in Rest I use Tiny.RestClient.

为了在 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();

回答by Anup

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