RestSharp-WCF REST服务未收到授权标头

本文关键字:授权 权标 REST 服务 RestSharp-WCF | 更新日期: 2023-09-27 18:24:06

我正在尝试使用基本身份验证通过HTTPS调用本地托管的WCF REST服务。

这很有效,授权标头通过得很好,一切都很好:

ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var request = (HttpWebRequest)WebRequest.Create("https://localhost/MyService/MyService.svc/");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add(
  System.Net.HttpRequestHeader.Authorization,
  "Basic " + this.EncodeBasicAuthenticationCredentials("UserA", "123"));
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
    if (webStream != null)
    {
        using (StreamReader responseReader = new StreamReader(webStream))
        {
            string response = responseReader.ReadToEnd();
        }
    }
}

然而,当我尝试使用RestSharp时,请求中从未出现授权标头:

ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var credentials = this.EncodeBasicAuthenticationCredentials("UserA", "123");
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");   
var restRq = new RestSharp.RestRequest("/");
restRq.Method = Method.GET;
restRq.RootElement = "/";
restRq.AddHeader("Authorization", "Basic " + credentials);
var restRs = client.Execute(restRq);

我用RestSharp方法做错了什么?

我知道AddHeader方法之所以有效,是因为:

restRq.AddHeader("Rum", "And Coke");

将通过,只有"授权"似乎被删除/丢失。

RestSharp-WCF REST服务未收到授权标头

不要"手动"添加标题,而是执行以下操作:

var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
client.Authenticator = new HttpBasicAuthenticator("UserA", "123");

我使用milano的答案使我的REST服务调用工作(使用get)

    Dim client2 As RestClient = New RestClient("https://api.clever.com")
    Dim request2 As RestRequest = New RestRequest("me", Method.GET)
    request2.AddParameter("Authorization", "Bearer " & j.access_token, ParameterType.HttpHeader)
    Dim response2 As IRestResponse = client2.Execute(request2)
    Response.Write("** " & response2.StatusCode & "|" & response2.Content & " **")

密钥是确保单词"Bearer"后面有一个空格,但这可能适用于任何类型的自定义令牌授权标头

您必须使用ParameterType.HttpHeader参数:

request.AddParameter("Authorization", "data", ParameterType.HttpHeader);

我能够使用以下代码从其余API获得响应:我的API返回服务器错误,我使用:

request.AddHeader("Authorization", $"Bearer {accessToken}");
var request = new RestRequest("/antiforgerytokensso", Method.Get);
restClient.Authenticator = new JwtAuthenticator(accessToken);
var response = await restClient.ExecuteAsync(request);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));