Search code examples
c#apiauthorizationrestsharp

Call api with dual authentication with restsharp


I'm brand new to restsharp and somewhat new to c# I am trying to use restsharp to access an api.

With powershell I can use.

$ClientCredsPlainText   = $ClientID + ":" + $ClientSecret
$ClientCredsBase64      = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($ClientCredsPlainText))
 
$AuthHeader = @{"Content-Type"  = 'application/x-www-form-urlencoded'
                "accept"        = 'application/json'
                "authorization" = "Basic $ClientCredsBase64" }
$AuthAPI    = @{"endpoint"      = 'https://foo.bar.com/api/'
                "url"           = '/now/table/cmdb_ci_server?u_owner_group=' }
$AuthBody   = @{"grant_type"    = 'password'
                "username"      = $SessionUser
                "password"      = $SessionPassword }

$finalresult=@()
$mdsownergroup=@('foo','bar','foofoo','barbar')
foreach ($item in $mdsownergroup) {
    $cmdburi        = $AuthAPI.endpoint + $AuthAPI.url + $item
    $cmdbrequest    = Invoke-RestMethod -Method GET -Uri $cmdburi -Headers $AuthHeader -Body $AuthBody 
    $finalresult+=$cmdbrequest.result 
    }
$cmdbrequest.result 

I am trying the same thing in c# with restsharp and postman suggests the following should work.

var client = new RestClient("https://foo.bar.com/api/");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("X-IBM-Client-Id", "xxxxxx");
request.AddHeader("Authorization", "[{\"key\":\"\",\"value\":\"xxxxxx",\"description\":\"\",\"type\":\"text\",\"enabled\":true}]");
request.AddHeader("Authorization", "Basic xxxx");
request.AddHeader("Cookie", "JSESSIONID=xxxxx glide_user_route=glide.xxxx glide_session_store=xxxx; BIGipServerpool_foo=209737994.35390.0000");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Using this I receive:

System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Authentication failed because the remote party has closed the transport stream.

Solution

  • Actually after reviewing with another dev it turns out I needed to use basic auth and remove the username and password. That is I over complicated by passing both client id and secret as well as username and password.