12

I'm trying to send a GET request with a token authentication, but i get an unauthorized response. If i send the same request on Postman, it works.

Here's my code :

string url = string.Format("{0}batchs", MyUrl);
RestClient client = new RestClient(url);
RestRequest getRequest = new RestRequest(Method.GET);
getRequest.AddHeader("Accept", "application/json");
getRequest.AddHeader("Authorization", "token " + MyToken);
getRequest.AddParameter("name", MyName, ParameterType.QueryString);

IRestResponse getResponse = client.Execute(getRequest);

And here's my postman request :

Postman request

Any ideas on how to correct this ?

Thanks !

Kévin Buzit
  • 141
  • 1
  • 1
  • 4

2 Answers2

16

I'm not sure exactly what kind of auth you're using, but I use a firebase token generated at runtime, and this is the only thing I could get to work for me.

request.AddHeader("authorization", "Bearer " + _fireBaseService.AuthToken);
Swisscheese
  • 571
  • 1
  • 5
  • 21
0

I encountered a similar problem in my implementation. I've explored various solutions, but none of them have been effective so far. Eventually, I discovered that Postman handles HTTP redirection automatically. However, when using RestSharp for implementation, the headers we initially set are not included in the redirected request.

To verify, disable the "Automatically follow redirects" setting in Postman. After turning off this setting, if the issue still persists in Postman, it indicates that the problem lies in the extraction process.

enter image description here

So I added a check that resends the API request of receiving a 401 with the below code.

... rest of your code

RestResponse response = await client.ExecuteAsync(request);

int numericStatusCode = (int)response.StatusCode;
if (numericStatusCode == 401)
{
       var redirectedClient = new RestClient(response.ResponseUri.ToString());
       var newResponse = redirectedClient.Execute(request);
       Console.WriteLine(newResponse.ResponseStatus);
}

Here is my full code:

var url = $"{_apiCredentials.DataServer}/test/data/contracts/";

var options = new RestClientOptions(url)
{
       MaxTimeout = -1,
       Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(
                accessToken.Token, // Update the token
                "Bearer")
};

var client = new RestClient(options);
var request = new RestRequest("", Method.Get);

RestResponse response = await client.ExecuteAsync(request);

int numericStatusCode = (int)response.StatusCode;
if (numericStatusCode == 401)
{
      var redirectedClient = new 
      RestClient(response.ResponseUri.ToString());
      var newResponse = redirectedClient.Execute(request);
      Console.WriteLine(newResponse.ResponseStatus);
}
shalitha senanayaka
  • 1,905
  • 20
  • 37