Using HttpClient with the RightScale API

1.5k Views Asked by At

I'm trying to use the WCF Rest Starter Kit with the RightScale's Login API which seems fairly simple to use.

Edit - Here's a blog entry I wrote on using Powershell to consume the API.

Edit - Created a generic .NET wrapper for the RightScale API - NRightAPI

It's exactly as simple as it looks while using CURL. In order for me to obtain a login cookie all I need to do is:

curl -v -c rightcookie -u username:password "https://my.rightscale.com/api/acct/accountid/login?api_version=1.0"

And I receive the following cookie:

HTTP/1.1 204 No Content Date: Fri, 25
Dec 2009 12:29:24 GMT Server: Mongrel 1.1.3 Status: 204 No Content X-Runtime: 0.06121
Content-Type: text/html; charset=utf-8
Content-Length: 0
Cache-Control: no-cache
Added cookie _session_id="488a8d9493579b9473fbcfb94b3a7b8e5e3" for domain my.rightscale.com, path /, expire 0
Set-Cookie: _session_id=488a8d9493579b9473fbcfb94b3a7b8e5e3; path=/; secure Vary: Accept-Encoding

However, when I use the following C# code:

HttpClient http = new HttpClient("https://my.rightscale.com/api/accountid/login?api_version=1.0");
http.TransportSettings.UseDefaultCredentials = false;
http.TransportSettings.MaximumAutomaticRedirections = 0;
http.TransportSettings.Credentials = new NetworkCredential("username", "password");
Console.WriteLine(http.Get().Content.ReadAsString());

Instead of a HTTP 204, I get a redirect:

You are being <a> href="https://my.rightscale.com/dashboard">redirected <a>

How do I get the WCF REST starter kit working with the RighScale API ?

1

There are 1 best solutions below

5
On

I needed to add a "Authorization: Basic " header to my request.

In additional to the initial code I had posted:

HttpClient http = new HttpClient("https://my.rightscale.com/api/acct/accountid/login?api_version=1.0");
http.TransportSettings.UseDefaultCredentials = false;
http.TransportSettings.MaximumAutomaticRedirections = 0;
http.TransportSettings.Credentials = new NetworkCredential("username", "password");

I need to add the Authorization header along with the REST request with the username/password as follows:

byte[] authbytes = Encoding.ASCII.GetBytes(string.Concat("username",":", "password"));
string base64 = Convert.ToBase64String(authbytes);
string authorization = string.Concat("Authorization: Basic ", base64);
http.DefaultHeaders.Add(authorization);

And then when I made the request:

Console.WriteLine(http.Get().Content.ReadAsString());

I received the HTTP 204 along with the session cookie I was looking for. What can I say, Fiddler is awesome :) !