3

I'm working on a C# Windows Form application and I would like to have the ability to test a users' credentials against Jira. Basically the user would input their username and password, click OK and the program will tell them if their credentials are accepted or not.

I already have working code (see below) that uses basic authentication via HttpWebRequest to create new tickets (aka issues), close tickets, add watchers, etc - so I figured this would be easy but I'm struggling with it.

As an analog, you can do a credentials check against Active Directory very easily using the System.DirectoryServices.AccountManagement namespace. Basically the method authenticateAD() will simply return true or false:

private bool authenticateAD(string username, string password)
{
    PrincipalContext pc = new PrincipalContext(ContextType.Domain, "example.com");
    bool isValid = pc.ValidateCredentials(username,password);
    return isValid;
}

This is exactly the kind of thing I want to do with Jira.

For reference, here's the code I'm using to add/close/update tickets in jira - maybe it can be modified to do what I want?

private Dictionary<string, string> sendHTTPtoREST(string json, string restURL)
{
    HttpWebRequest request = WebRequest.Create(restURL) as HttpWebRequest;
    request.Method = "POST";
    request.Accept = "application/json";
    request.ContentType = "application/json";
    string mergedCreds = string.Format("{0}:{1}", username, password);
    byte[] byteCreds = UTF8Encoding.UTF8.GetBytes(mergedCreds);
    request.Headers.Add("Authorization", "Basic " + byteCreds);
    byte[] data = Encoding.UTF8.GetBytes(json);
    try
    {
        using (var requestStream = request.GetRequestStream())
        {
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();
        }
    }
    catch(Exception ex)
    {
        displayMessages(string.Format("Error creating Jira: {0}",ex.Message.ToString()), "red", "white");
        Dictionary<string, string> excepHTTP = new Dictionary<string, string>();
        excepHTTP.Add("error", ex.Message.ToString());
        return excepHTTP;
    }
    response = (HttpWebResponse)request.GetResponse();
    var reader = new StreamReader(response.GetResponseStream());
    string str = reader.ReadToEnd();
    var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
    var sData = jss.Deserialize<Dictionary<string, string>>(str);

    if(response.StatusCode.ToString()=="NoContent")
    {
        sData.Add("code", "NoContent");
        request.Abort();
        return sData;
    }
    else
    {
        sData.Add("code", response.StatusCode.ToString());
        request.Abort();
        return sData;
    }
}

Thanks!

1

2 Answers 2

1

How about attempting to access the root page of JIRA and see if you get an HTTP 403 error?

        try
        {
            // access JIRA using (parts of) your existing code
        }
        catch (WebException we)
        {
            var response = we.Response as HttpWebResponse;
            if (response != null && response.StatusCode == HttpStatusCode.Forbidden)
            {
                // JIRA doesn't like your credentials
            }
        }
Sign up to request clarification or add additional context in comments.

Comments

0

The HttpClient would be simple and best to use check credentials with GetAsync.

The sample code is below

using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(JiraPath);
                // Add an Accept header for JSON format.
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string mergedCreds = string.Format("{0}:{1}", username, password);
byte[] byteCreds = UTF8Encoding.UTF8.GetBytes(mergedCreds);
                var authHeader = new AuthenticationHeaderValue("Basic", byteCreds);
                client.DefaultRequestHeaders.Authorization = authHeader;
                HttpResponseMessage response = client.GetAsync(restURL).Result;  // Blocking call!
                if (response.IsSuccessStatusCode)
                {
                    strJSON = response.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(strJSON))
                        return strJSON;
                }
                else
                {
                    exceptionOccured = true;
                    // Use "response.ReasonPhrase" to return error message

                }
            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.