GET request with basic auth works from Postman but not from C#

Viewed 2366

I have the following simple GET request with Basic Auth that works fine from Postman:

enter image description here

I then just copy/paste the C# - RestSharp code snippet from postman into a simple console application:

class Program
{
    static void Main(string[] args)
    {
        var client = new RestClient("https://.....");
        client.Timeout = -1;
        var request = new RestRequest(Method.GET);
        request.AddHeader("X-CSRF-Token", "Fetch");
        request.AddHeader("Authorization", "Basic U0.....==");
        IRestResponse response = client.Execute(request);            

        ....

but the response is: 401 Not Authorized.

I've always used the auto-generated snippets form Postman with no problems so far. But now I'm facing this issue, apparently sth is missing from the request made with C# code.

Any advice or pointers would be much appreciated!

UPDATE: Using curl on windows 10 the request works ok. This is what I used:

curl --location --request GET "https://....." --header "X-CSRF-Token: Fetch" --header "Authorization: Basic ......"

The auth token is exactly the same in both cases, in curl it works in RestSharp it doesn't.

3 Answers

Here's my example, check your ssl. The endpoint setting has Nginx, SSL self-signed certificate, basic auth.

using System;
using RestSharp;
using RestSharp.Authenticators;

namespace StackOverflow
{
  class Program
  {
    static void Main(string[] args)
    {
      var client = new RestClient("https://10.0.1.98");
      client.Timeout = -1;
      // Auth
      client.Authenticator = new HttpBasicAuthenticator("patricio", "myStrongPwd");
      // bypass self-signed certificate verification
      client.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
      var request = new RestRequest(Method.GET);
      IRestResponse response = client.Execute(request);   
      Console.WriteLine(response.StatusCode);
    }
  }
}

It's not a great answer, but I think there must be some other header or property within your Postman request that is missing from your C# example.

To double check, I used a Postman request with no username and a password as per your example. I then copied the header stringcopied the header from Postman

A quick unit test later and the code I used have many times before (very similar to the comments)

    [Test]
    public void PostmanEncodesCredentialsProperly()
    {
        var password = "a temporary cred";
        var expected = "Basic OmEgdGVtcG9yYXJ5IGNyZWQ=";

        var header = GetBasicAuthHeader(string.Empty, password);

        Assert.That(header, Is.EqualTo(expected));
    }

    private string GetBasicAuthHeader(string user, string password)
    {
        var cred = $"{user}:{password}";
        var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(cred));
        return $"Basic {encoded}";
    }

shows that Postman is encoding exactly what you would expect.

I could not spot a ContentType, UserAgent for the Request processing you have implemented.

if (RequestMethod == MethodENU.RequestMethod.GET)
{

    webReqeust = (HttpWebRequest)WebRequest.Create(string.Format("{0}{1}", requestURI, queryString));
    if (authorizationHeader == true)
    {
        webReqeust.Headers.Add("Key", "KeyValue");
    }

    webReqeust.Method = RequestMethod.ToString(); // ReqeustMethod Object Is an ENUM of possible Reqeust Methods, GE
    if (ContentType == MethodENU.ContentType.JSON) // Using Different Content Types Accodring to Requirement.
    {
        webReqeust.ContentType = "application/json";  
    }
    else if (ContentType == MethodENU.ContentType.FORM_DATA)
    {
        webReqeust.ContentType = "multipart/form-data";
    }
    webReqeust.UserAgent = "Mozilla/5.0"; // Setting a UserAgent
    resp = (HttpWebResponse)webReqeust.GetResponse();
    using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
    {
        responseData = reader.ReadToEnd();
    }
}

Enumerations used in the above sample code.

public enum RequestMethod
{
    GET,
    POST,
    PUT
}

public enum ContentType
{
    JSON,
    FORM_DATA
}

Also, Did you try to catch the request and response using some tool like Fiddler? How are the responses in both the cases, PostMan and CodeBase?

Related