使用 restsharp 使用双重身份验证调用 api

Call api with dual authentication with restsharp

我是 restsharp 的新手,也是 c# 的新手 我正在尝试使用 restsharp 访问 api.

有了powershell我就可以用了

$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 

我在 c# 中使用 restsharp 尝试同样的事情,邮递员建议以下应该有效。

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

使用这个我收到:

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.

实际上,在与另一位开发人员一起审查后,我发现我需要使用基本身份验证并删除用户名和密码。通过传递客户端 ID 和密码以及用户名和密码,我太复杂了。