Geo*_*ang 4 restsharp oauth-2.0 auth0
我尝试使用 Postman 将不记名令牌发送到 Auth0 API,效果非常好。
然后我尝试使用 RestSharp (在 c# 中)进行相同的操作,但它根本不起作用。
下面是我的代码。我尝试了许多不同的格式,但没有一个能工作。我还有其他方法可以尝试使其工作吗?
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
| 归档时间: | 
 | 
| 查看次数: | 3845 次 | 
| 最近记录: |