发送 OAuth 令牌在 Postman 中有效,但在 RestSharp 中无效

Sending OAuth token works in Postman but does not work in RestSharp

我尝试使用 Postman 将不记名令牌发送到 Auth0 API,并且效果很好。

然后我使用 RestSharp(在 c# 中)尝试了相同的方法,但它根本不起作用。

下面是我的代码。我已经尝试了很多不同的格式,但其中 none 行得通。有没有其他方法可以尝试让它行得通?

var client = new RestClient("http://domain.auth0.com/api/v2/users");

RestRequest request = new RestRequest(Method.GET);
//request.AddHeader("authorization", "Bearer eyJhbGcJ9.eyJhdWQiOiJ6VU4hVWUE2.token");
//request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
//request.AddHeader("Accept", "application/json");


//RestClient client = new RestClient("http://domain.auth0.com");
//RestRequest request = new RestRequest("api/v2/users", Method.GET);

request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.AddParameter("Authorization",
string.Format("Bearer " + "eyJhbGciOI1NiIsI9.eyJhdWQiOiWmVhTWpD2VycyI6eyJhY.token"),
            ParameterType.HttpHeader);

//request.AddParameter("Authorization",
//    String.Format("Bearer {0}", token),
//ParameterType.HttpHeader);
var response = client.Execute(request); 

PS: 令牌已更改。

问题是您使用的是 HTTP URL。当您发出第一个请求时,令牌已包含在内,但您会收到重定向响应,通知您应该调用 HTTPS 端点。

由于 RestSharp 不会在由于第一个重定向响应而自动执行的第二个请求中包含令牌,因此您会收到未经授权的响应。

您需要将 URL 更新为 HTTPS,这将阻止重定向,从而解决您的问题。如果您想使用同一个客户端发出多个经过身份验证的请求,您还可以将代码更改为:

using RestSharp;
using RestSharp.Authenticators;

class Program
{
    static void Main(string[] args)
    {
        // Use the HTTPS scheme
        var client = new RestClient("https://[domain].auth0.com/api/v2/users");

        client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(
            "eyJhbGciJIUz.eyJhdWQi4QW5OXhCNTNlNDdjIn0.vnzGPiWA", // Update the token
            "Bearer");

        var request = new RestRequest(Method.GET);

        IRestResponse response = client.Execute(request);

        Console.WriteLine("{0}", response.StatusCode);
    }
}

如果您确实需要处理重定向并仍然发送令牌,请检查:https://github.com/restsharp/RestSharp/issues/414