It's all about the answers!

Ask a question

RRC , C# Catalog Authentication mode Code !


Akshansh Khare (5678) | asked Jan 23 '12, 7:58 a.m.
Hi All,

I am developing a application in c# which will get count of different things from my RRC , I have developed the code for RTC and it seems to work all fine , but when that same code i use for RRC it gives me 401 Authentication error.

For RTC i have used basic authentication.


HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(TxtURL.Text);

Request.Accept = @"application/xml";
Request.Headers.Add("OSLC-Core-Version", "2.0");
Request.Credentials = new NetworkCredential(TxtUserID.Text, TxtPwd.Text);
Request.Timeout = 3600000;


I guess that RRC uses Form authentication and post to URI./j_security_check with the two parameter j_username and j_password.
I tried to do it that way, but no success.

Can you please help me for RRC ?
Some insight about RRC authentication in c# is greatly appreciated.


Akki

11 answers



permanent link
Jared Russell (1.3k12019) | answered Jan 23 '12, 12:09 p.m.
Authenticating via forms auth is a two stage process. You first need to make a GET request to the /authenticated/identity URL in order to get a cookie from the server, then you need to POST to the /authenticated/j_security_check URL with the username and password, passing the cookie along with the request. Code example is below:

namespace ConsoleApplication1

{
class Program
{
static void Main(string[] args)
{
var host = "localhost";
var port = "9443";
var baseUrl = string.Format("https://{0}:{1}", host, port);

var container = new CookieContainer();

//Make initial request to get a cookie
var request = (HttpWebRequest)WebRequest.Create(baseUrl + "/jts/authenticated/identity");
request.CookieContainer = container;
request.Method = WebRequestMethods.Http.Get;
var response = request.GetResponse();

//Attempt to authenticate with the server
var username = "ADMIN";
var password = "ADMIN";
var request2 = (HttpWebRequest)WebRequest.Create(
string.Format(baseUrl + "/jts/authenticated/j_security_check?j_username={0}&j_password={1}",
username,
password));
request2.CookieContainer = container;
request2.Method = WebRequestMethods.Http.Post;
request2.ContentType = "application/x-www-form-urlencoded";
var response2 = request2.GetResponse();
if (response2.Headers["X-com-ibm-team-repository-web-auth-msg"] != null)
{
Console.WriteLine("Username or password incorrect");
return;
}

Console.WriteLine("Login successful");

}
}
}


Hi All,

I am developing a application in c# which will get count of different things from my RRC , I have developed the code for RTC and it seems to work all fine , but when that same code i use for RRC it gives me 401 Authentication error.

For RTC i have used basic authentication.


HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(TxtURL.Text);

Request.Accept = @"application/xml";
Request.Headers.Add("OSLC-Core-Version", "2.0");
Request.Credentials = new NetworkCredential(TxtUserID.Text, TxtPwd.Text);
Request.Timeout = 3600000;


I guess that RRC uses Form authentication and post to URI./j_security_check with the two parameter j_username and j_password.
I tried to do it that way, but no success.

Can you please help me for RRC ?
Some insight about RRC authentication in c# is greatly appreciated.


Akki

permanent link
Akshansh Khare (5678) | answered Jan 24 '12, 1:46 a.m.
Thanks a lot Jared Russell.
This is what i was looking for.
:)

permanent link
Akshansh Khare (5678) | answered Jan 24 '12, 1:57 a.m.
One more question Jared.

I was trying to use RQM and C# Dot Net to again build a similar console application.I went to the root services of RQM from where i got the workitem catalog(https://host:port/qm/oslc/workitems/catalog)
, but this catalog returns me a HTML response.
How can i get the project areas that are present in the RQM.

Thanks a lot for your help again.

Akki

permanent link
Jared Russell (1.3k12019) | answered Jan 24 '12, 7:27 a.m.
The two things I can think of off the top of my head:

- Ensure you've authenticated with RQM successfully. IIRC you can get the rootservices doc without logging in, but you'll get a login challenge (in HTML) if you try and request any of the lower level services. If you're using forms auth make sure you pass the same CookieContainer with all of your requests.
- Ensure you've set the Accept header of the request to "application/xml"

One more question Jared.

I was trying to use RQM and C# Dot Net to again build a similar console application.I went to the root services of RQM from where i got the workitem catalog(https://host:port/qm/oslc/workitems/catalog)
, but this catalog returns me a HTML response.
How can i get the project areas that are present in the RQM.

Thanks a lot for your help again.

Akki

permanent link
Ravi Kaushal (21) | answered Feb 08 '12, 8:04 a.m.
Hi guys,

We are trying to connect to a RRC repository for fetching some details for plug-in development. While doing so we are getting the following error - 408 Request Timeout.

The code is :

/* A sample code for connecting to the RRC Repository */

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var host = "host";
var port = "9443";
var baseUrl = string.Format("https://{0}:{1}", host, port);

var container = new CookieContainer();

//Make initial request to get a cookie
try
{
//tackles the digital security certificate error
ServicePointManager.ServerCertificateValidationCallback +=
delegate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};
}
catch (Exception exp3)
{
Console.WriteLine(exp3.Message);
}
try
{
var request = (HttpWebRequest)WebRequest.Create(baseUrl + "/jts/admin");
request.CookieContainer = container;
request.Method = WebRequestMethods.Http.Get;
var response = (HttpWebResponse)request.GetResponse();
response.Close();
}
catch (Exception exp1)
{
Console.WriteLine(exp1.Message);
}
Console.WriteLine("Cookie created");
//Attempt to authenticate with the server
var username = "admin";
var password = "admin";
try
{
var request2 = (HttpWebRequest)WebRequest.Create(
string.Format(baseUrl + "/jts/admin/j_security_check?j_username={0}&j_password={1}",
username,
password));
request2.CookieContainer = container;
request2.Method = WebRequestMethods.Http.Post;
request2.Timeout = 1000000;
request2.ContentType = "application/x-www-form-urlencoded";
var response2 = request2.GetResponse();
if (response2.Headers != null)
{
Console.WriteLine("Username or password incorrect");
return;
}

Console.WriteLine("Login successful");
response2.Close();
}
catch (Exception exp2)
{
Console.WriteLine(exp2.Message);
}
Console.ReadLine();
}
}
}
Any pointers are welcome.
Please provide a C# sample code to connect to RRC and fetch details.

permanent link
Ravi Kaushal (21) | answered Feb 08 '12, 8:25 a.m.
Hi guys,

We are trying to connect to a RRC repository for fetching some details for plug-in development. While doing so we are getting the following error - 408 Request Timeout.

The code is :

/* A sample code for connecting to the RRC Repository */

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var host = "host";
var port = "9443";
var baseUrl = string.Format("https://{0}:{1}", host, port);

var container = new CookieContainer();

//Make initial request to get a cookie
try
{
//tackles the digital security certificate error
ServicePointManager.ServerCertificateValidationCallback +=
delegate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};
}
catch (Exception exp3)
{
Console.WriteLine(exp3.Message);
}
try
{
var request = (HttpWebRequest)WebRequest.Create(baseUrl + "/jts/admin");
request.CookieContainer = container;
request.Method = WebRequestMethods.Http.Get;
var response = (HttpWebResponse)request.GetResponse();
response.Close();
}
catch (Exception exp1)
{
Console.WriteLine(exp1.Message);
}
Console.WriteLine("Cookie created");
//Attempt to authenticate with the server
var username = "admin";
var password = "admin";
try
{
var request2 = (HttpWebRequest)WebRequest.Create(
string.Format(baseUrl + "/jts/admin/j_security_check?j_username={0}&j_password={1}",
username,
password));
request2.CookieContainer = container;
request2.Method = WebRequestMethods.Http.Post;
request2.Timeout = 1000000;
request2.ContentType = "application/x-www-form-urlencoded";
var response2 = request2.GetResponse();
if (response2.Headers != null)
{
Console.WriteLine("Username or password incorrect");
return;
}

Console.WriteLine("Login successful");
response2.Close();
}
catch (Exception exp2)
{
Console.WriteLine(exp2.Message);
}
Console.ReadLine();
}
}
}

permanent link
sam detweiler (12.5k6195201) | answered Mar 20 '12, 5:39 p.m.
I am trying to fix some old code which worked on 2.0.0.2.. and doesn't on 3.0.1.1

I have another topic posted about it..
https://jazz.net/forums/viewtopic.php?p=77164#77164

but

this makes no sense to me..

You first need to make a GET request to the /authenticated/identity URL in order to get a cookie from the serve

you don't get 'A' cookie from the server, you get THREE cookies.
JazzFormAuth=Form
Path=/ccm
JSESSIONID=82CF80BD6E055C93503C38012B229248

when I pass those back to the server I still get an authfailed response from the j_security_check postback..

I am not using Java so cannot use the cookiecontainer object.
(using salesforce apex)

if I post the userid/pw as parameters on the url, then I get a contentlength error.. if I post them in as part of the form data I still get authfailed..

I can logon with the userid and password via a browser.

permanent link
Ivanilto Souza (6) | answered Mar 21 '12, 6:04 p.m.
This code is working perfectly.
Next task is to make the xml parser.

public string AutenticRTC()
{
try
{
//tackles the digital security certificate error
System.Net.ServicePointManager.ServerCertificateValidationCallback =
delegate(object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
};
}
catch (Exception exp3)
{
return exp3.Message;
}
var host = "localhost";
var port = "9443";
var baseUrl = string.Format("https://{0}:{1}", host, port);
var container = new CookieContainer();
var request = (HttpWebRequest)WebRequest.Create(baseUrl + "/ccm/authenticated/identity");
request.CookieContainer = container;
request.Method = WebRequestMethods.Http.Get;
var response = request.GetResponse();
response.Close();
var username = txtUser.Text;
var password = txtPwd.Text;
var request2 = (HttpWebRequest)WebRequest.Create(
string.Format(baseUrl + "/ccm/authenticated/j_security_check?j_username={0}&j_password={1}",
username,
password));

request2.CookieContainer = container;
request2.Method = WebRequestMethods.Http.Get;
request2.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse response2 = (HttpWebResponse) request2.GetResponse();

String response2String = new StreamReader(response2.GetResponseStream()).ReadToEnd();

String l1;
if (response2.Headers != null)
{
l1 = "Username or password incorrect";
}else {
l1 = "Login successful";

HttpWebRequest request3 = (HttpWebRequest)WebRequest.Create(baseUrl + "/ccm/oslc/workitems/1234.xml?oslc_cm.properties=dc:identifier,dc:title,rtc_cm:due,dc:created,rtc_cm:resolved,rtc_cm:state{dc:title},rtc_cm:com.ibm.team.workitem.linktype.parentworkitem.children{dc:title}");
request3.CookieContainer = container;
request3.Method = WebRequestMethods.Http.Get;

HttpWebResponse response3 = (HttpWebResponse) request3.GetResponse();

String responseString = new StreamReader(response3.GetResponseStream()).ReadToEnd();
l1 = l1 + responseString;
}
return l1;

}


protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = AutenticRTC();
}

permanent link
Brijraj Beriwal (1311417) | answered Sep 26 '12, 5:54 a.m.

Incontinuation of the above question could anyone please give a sample code to add requiremnts ,testcases and linking them.....?

Also if possible could anyone please give any url which gives sample code for working on RQM using C# .net4.0..?


permanent link
navneet kumar (02) | answered Jun 13 '13, 1:21 a.m.
 There are two ways by which you can perform form authentication - 
1. Using WebClient class 
2. Using HTTPWebRequest/HTTPWebResposne class

I would recommend using the WebClient class. Here is the sample code - 
1. webclient class
public class WebClientExtension : WebClient
    {
        //cookie container
        private CookieContainer _ckContainer = new CookieContainer();

        //request server 
        protected override WebRequest GetWebRequest(Uri _url)
        {
            WebRequest _request = base.GetWebRequest(_url);
            if (_request is HttpWebRequest)
            {
                (_request as HttpWebRequest).CookieContainer = _ckContainer;
            }
            return _request;
        }
    }
   class Program
    {
        static void Main()
        {
            //create object of WebClientExtension class
            using (var _webClient = new WebClientExtension())
            {
                var _serverResponse1 = _webClient.DownloadString("https://localhost:9443/jazz/authenticated/identity");
                //set username and password
                var data = new NameValueCollection
            {
                { "j_username", "UserName" },
                { "j_password", "Password" },
            };
                //authenticate
                var _serverResponse2 = _webClient.UploadValues("https://localhost:9443/jazz/authenticated/j_security_check", data);
                Console.WriteLine(Encoding.Default.GetString(_serverResponse2));
            }
        }
    }
	
	
2. HTTPWebrequest/HTTPWebresponse class:

 public static HttpWebResponse requestSecureDocument(HttpWebRequest _request, string _rtcServerURL, string _userName, string _password)
        {
             //FormBasedAuth Step1: Request the resource and clone the request to be used later
            HttpWebRequest _requestClone = WebRequestExtensions.CloneRequest(_request, _request.RequestUri);//(HttpWebRequest)WebRequest.Create(request.RequestUri);

            //store the response in _docResponse variable
            HttpWebResponse _docResponse = (HttpWebResponse)_request.GetResponse();

            //HttpStatusCode.OK indicates that the request succeeded and that the requested information is in the response.
            if (_docResponse.StatusCode == HttpStatusCode.OK)
            {
                //X-com-ibm-team-repository-web-auth-msg header signifies form based authentication is being used
                string _rtcAuthHeader = _docResponse.Headers["X-com-ibm-team-repository-web-auth-msg"];
                if ((_rtcAuthHeader != null) && _rtcAuthHeader.Equals("authrequired"))
                {
                    _docResponse.GetResponseStream().Flush();
                    _docResponse.Close();

                    //Prepare form for authentication as _rtcAuthHeader = authrequired
                    HttpWebRequest _formPost = (HttpWebRequest)WebRequest.Create(_rtcServerURL + "/j_security_check");
                    _formPost.Method = "POST";
                    _formPost.Timeout = 30000;
                    _formPost.CookieContainer = _request.CookieContainer;
                    _formPost.Accept = "text/xml";
                    _formPost.ContentType = "application/x-www-form-urlencoded";

                    String _authString = "j_username=" + _userName + "&j_password=" + _password; //create authentication string
                    Byte[] _outBuffer = Encoding.UTF8.GetBytes(_authString); //store in byte buffer
                    _formPost.ContentLength = _outBuffer.Length;
                    Stream _str = _formPost.GetRequestStream();
                    _str.Write(_outBuffer, 0, _outBuffer.Length); //update form
                    _str.Close();

                    //FormBasedAuth Step2:submit the login form and get the response from the server
                    HttpWebResponse _formResponse = (HttpWebResponse)_formPost.GetResponse();

                    _rtcAuthHeader = _formResponse.Headers["X-com-ibm-team-repository-web-auth-msg"];
                    //check if authentication has failed
                    if ((_rtcAuthHeader != null) && _rtcAuthHeader.Equals("authfailed"))
                    {
                         //authentication failed. You can write code to handle the authentication failure.
                        //if (DEBUG) Console.WriteLine("Authentication Failure");
                    }
                    else
                    {
                        //login successful
                        _formResponse.GetResponseStream().Flush();
                        _formResponse.Close();
                        //FormBasedAuth Step3: Resend the request for the protected resource.
                        //if (DEBUG) Console.WriteLine(">> Response " + request.RequestUri);
                        return (HttpWebResponse)_requestClone.GetResponse();
                    }
                }
            }
            //already authenticated return original response_docResponse
            return _docResponse;
        }
	
and here is how you consume it :
            string _serverURL = https://localhost:9443/ccm; 
            string _resourceURL = "https://localhost:9443/ccm/rootservices";

            string mediatype = "application/xml";
            string username = "username";                                    
            string password = "password";
            try
            {
                CookieContainer _cookies = new CookieContainer();//create cookie container
                HttpWebRequest documentGet = (HttpWebRequest)WebRequest.Create(_resourceURL);
                documentGet.Method = "GET"; //method
                documentGet.CookieContainer = _cookies; //set container for HttpWebRequest 
                documentGet.Accept = mediatype;
                documentGet.Headers.Set("OSLC-Core-Version", "3.0"); //for RTC 3.0.1.2
                documentGet.Timeout = 300000;
                HttpWebResponse response = requestSecureDocument(documentGet, _serverURL, username, password);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    Console.WriteLine(" Error: " + response.StatusDescription);
                    response.Close();
                }
            }
            catch (Exception ex)
            {
            }
	

Comments
Andrew Trobec commented Jun 18 '13, 10:43 a.m. | edited Jun 18 '13, 10:46 a.m.

@navneet83


I tried the first option but I always get the error

The remote server returned an error: (401) Unauthorized.

when trying to get the cookie:

var _serverResponse1 = _webClient.DownloadString("https://<server>/jts/authenticated/identity");

I am using RTC 4.0.0.1.

Any ideas?

Regards,

Andrew

Your answer


Register or to post your answer.


Dashboards and work items are no longer publicly available, so some links may be invalid. We now provide similar information through other means. Learn more here.