3

When we have this curl command:

curl -XPUT "https//auth.something.com"
-u "clientId:clientSecret"

What should I do to convert it into C#?

NetworkCredential myCred = new NetworkCredential(clientKey, clientSecret);

or this: https://stackoverflow.com/a/34649812/5531761

or webClient.Headers[HttpRequestHeader.Authorization] = "Basic " + based64; (Why should you base64 encode the Authorization header?)

Or CredentialCache (https://stackoverflow.com/a/3996838/5531761)


My curl conversion

using(var webClient = new WebClient()){
    webClient.UploadString("https//auth.something.com","PUT","{ \"data\":\"dummy data\" }");
}
Dylan Czenski
  • 1,305
  • 4
  • 29
  • 49

2 Answers2

3

Is this what you're looking for?

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("base address");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("clientId" + ":" + "clientSecret")));

Update: based on the updated question

I haven't tried this yet, but could you test this?

using(var webClient = new WebClient())
{
    webClient.Headers.Add("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("clientId" + ":" + "clientSecret")));
    webClient.UploadString("https//auth.something.com","PUT","{ \"data\":\"dummy data\" }");    
}
Dylan Czenski
  • 1,305
  • 4
  • 29
  • 49
AD8
  • 2,168
  • 2
  • 16
  • 31
0

If can't or won't use HttpClient you can use HttpWebRequest:

string postData= "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] data = encoding.GetBytes (postData);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create ("http://target.com");
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential ("username", "password");;
request.Method = "PUT";
request.ContentType =  "application/x-www-form-urlencoded";
request.ContentLength = data.Length;    
using (Stream stream = request.GetRequestStream ()) {
    stream.Write (data, 0, data.Length);
}    
var response = (HttpWebResponse)request.GetResponse ();
response.Close ();

MSDN documentation.

Alternative authentification options are:

  • request.Headers["Authorization"] = "Basic " + Convert.ToBase64String*Encoding.ASCII.GetBytes(authInfo));
    HTTP Basic authentication requies everything after "Basic " to be Base64-encoded

  • httpWebRequest.Headers.Add("Authorization: OAuth "+acces_token);

wp78de
  • 18,207
  • 7
  • 43
  • 71
  • kinda off topic but what if you have 2 params like "grant_type=client_credtials" and then "name=abc" – Dylan Czenski Jun 07 '18 at 04:31
  • Sure, you can have multiple URL params, e.g. `string.Format("id={0}&name={1}&inputPassword={2}", 123, email, password);` – wp78de Jun 07 '18 at 04:44