【问题标题】:Call api with dual authentication with restsharp使用restsharp调用具有双重身份验证的api
【发布时间】:2023-03-29 14:47:01
【问题描述】:

我是 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.

【问题讨论】:

  • 欢迎来到 SO。您提到您正在“做同样的事情”,但第二段代码似乎并不反映第一段代码。请避免发布“简化版本”。可重复的小样本很好,但它们必须包含我们为您提供帮助所需的一切。
  • 我想更清楚。我相信我正在做同样的事情。这是我正在使用的 powershell 代码和邮递员建议的 c#。
  • 知道了。 PowerShell 版本正在添加带有凭据的密码授权。我在 C# 版本的任何地方都看不到这一点。我也没有在 PowerShell 版本中看到任何 cookie。
  • 我发现了别的东西。我认为你想做一个 POST,而不是一个 GET。
  • 查看答案。以下。谢谢。

标签: c# api authorization restsharp


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-11-09
    • 1970-01-01
    • 2012-05-09
    • 2019-07-20
    • 2014-05-12
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多