This is my simple spike code:
var url = "http://url.de";
var username = "user";
var password = "password";
var client = new HttpClient();
var base64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64);
var result = client.GetAsync(url).Result;
On my Ubuntu server I always get a 401 authentication error with this code.
When I fire the webservice data on the same machine with Postman, the call works.
If I run the code directly on the webservice server (Windows Server) itself, the call works too.
What can be the problem?
Firewall is disabled.
I found the problem.
For whatever reason, the call via the code only works over HTTPS.
Related
I need to send data to a cgi script with POST method. If I try my code with fiddler capturing on, it works, if I shutdown fiddler it doesn work. Why this weird behaviour?
The script cgi is on a sms machine that sends SMS. If I run my code from Visual Studio 2019 with external fiddler process running, I correctly get this response: errno=0&desc=SMS Queued&SmsIndex=4
If I close fiddler and I run my code I get the error: errno=2&desc=Destination number missing.
I've also figured out that if I stop fiddler from capturing http traffic and I set in my code a WebProxy on http://localhost:8888 it works...BUT, if I close fiddler, that proxy shutdown and my code doesn't work any more.
I need to post data with no proxy, how can I do?
I tried both with .NET framework objects and with RestSharp: same issue!
This is my code .NET Framework code:
Dictionary<string,string> smsData = new Dictionary<string, string>{
{ "num", number },
{ "text", text },
{ "Push", push.ToString() },
{ "Pwd", password },
};
FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(smsData);
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://" + ip + "/smssend.cgi");
httpRequestMessage.Content = formUrlEncodedContent;
HttpResponseMessage res = _httpClient.SendAsync(httpRequestMessage).Result;
return res.Content.ReadAsStringAsync().Result;
This is my .NET Framework code with RestSharp library:
RestClient client = new RestClient("http://" + ip + "/smssend.cgi");
RestRequest request = new RestRequest("", Method.POST);
request.AddParameter("num", number);
request.AddParameter("text", text);
request.AddParameter("Push", push.ToString());
request.AddParameter("Pwd", password);
RestResponse response = (RestResponse) client.Execute(request);
return response.Content.ToString();
I solved by using TcpClient and NetworkStream
Im having major dramas getting the Amazon Alexa address api to work in the C# Web Api app i have created using AlexaSkillsKit.Net
var apiEndpoint = context.System.ApiEndpoint;
var deviceId = context.System.Device.DeviceId;
var apiAccessToken = context.System.ApiAccessToken;
var url = string.Format("{0}/v1/devices/{1}/settings/address", apiEndpoint, deviceId);
var client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiAccessToken);
client.DefaultRequestHeaders.Add("User-Agent", "Request-Promise");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string response = client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;
The response i get back is as follows:
{"type":"FORBIDDEN","message":"The authentication token is not valid."}
Im at a loss as to why im getting this error
I have given my app permissions to get the Full Address
I have got this to work, i just needed to send the Permissions Card back to the user
https://developer.amazon.com/docs/custom-skills/device-address-api.html
I can get an access token of Office 365. I can not make a REST request (GET) attaching this token in the header.
I'm using this code:
RestClient client = new RestClient();
client.EndPoint = #"https://outlook.office365.com/api/v1.0/me/folders/inbox/messages?$top=10";
client.Method = HttpVerb.GET;
client.ContentType = "application/json";
client.PostData = "authorization: Bearer " + myAccesToken.ToString();
String json = client.MakeRequest();
I've tested the access token in http://jwt.calebb.net and it's ok.
But it's always returning:
The remote server returned an error: (400) Bad Request.
I'm kind a knewby to REST and my english is not that good... Sorry! :)
(RE)EDIT
I've tried with RestSharp and I've simplified a bit my code...
Now I'm using my access token to make the GET request.
How do I add the "authorization bearer" to my request?
Is it like this?
//Ask for the token
var client = new RestClient("https://login.windows.net/common/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddParameter("grant_type", "authorization_code");
request.AddParameter("code", Request.QueryString["code"]);
request.AddParameter("redirect_uri", myRedirectUri);
request.AddParameter("client_id", myClientID);
request.AddParameter("client_secret", myClientSecret);
IRestResponse response = client.Execute(request);
string content = "[" + response.Content + "]";
DataTable dadosToken = (DataTable)JsonConvert.DeserializeObject<DataTable>(content);
//I don't need a DataTable, but it was a way to retrieve my access token... :)
//Ask for info with the access token
var client2 = new RestClient("https://outlook.office365.com/api/v1.0/me");
var request2 = new RestRequest(Method.GET);
request2.AddHeader("authorization", myToken.ToString());
//I've tried this way also:
//client2.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(dadosToken.Rows[0]["access_token"].ToString(), "Bearer");
IRestResponse response2 = client2.Execute(request2);
string content2 = "[" + response2.Content + "]";
Response.Write(content2); //this returns NOTHING!
Thanks again!
You can also use Fiddler to figure out if the Request is well formed.
Try a simpler endpoint first like: https://outlook.office365.com/api/v1.0/me
and check if the right data comes back. You can call this endpoint just from the browser and also look at the request/respond inside Fiddler.
The first thing to check: Is it a bad request. This usually means the method can't be found or the given parameters cannot be located. Check the deploy and make sure it is the most up to date version and also check that your server is actually running.
Problem: This code works fine from my local machine, but NOT on the server itself. (E.G. I can run this Linqpad script from my machine, I get a 200 and some data. I copy it to the server where the app is hosted and I get a 401. Why!? App has Windows Auth only enabled, NTLM only.
//Create REST client
var client = new RestClient("https://app.com/service/")
{
//Windows Auth
Authenticator = new NtlmAuthenticator("test\\test", "9##903f")
};
//Create Request to be sent
var request = new RestRequest("api/dogs/furriest");
//Create params to send
var parameters = new {
FurryLevel = 1,
CuteLevel = 2
};
//Add params to request
request.AddParameter("application/json", parameters.ToJson(), ParameterType.RequestBody);
//Execute the request
var response = client.ExecuteAsPost(request, "POST");
Do you enable windows authentication on your IIS site ?
I'm trying to create a https client in C#.
I had HTTP client which worked fine and I changed it to work with HTTPS. But unfortunately there is something wrong with the authorization (the server uses OAuth 2).
My program sends a request to a server and gets the token. But it can't get or send any data from the server.
The server works fine with other clients, so it's not its fault.
This is a piece of code which causes the problem. I know that, because when I comment authorization on the server, the data is send (everything is fine).
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("Authorization: {0}", token))));
This is the whole function, which should send data:
WebRequestHandler handler = new WebRequestHandler();
X509Certificate certificate = GetMyX509Certificate();
handler.ClientCertificates.Add(certificate);
var client = new HttpClient(handler);
string uri = "https://192.168.0.10:8443/data";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("Authorization: {0}", token))));
client.BaseAddress = new Uri(uri);
var parameters = new Dictionary<string, string>();
parameters["name"] = name;
parameters["surname"] = surname;
JavaScriptSerializer serializer = new JavaScriptSerializer();
var json = serializer.Serialize(parameters);
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
var response = client.PostAsync(uri, new StringContent(json, System.Text.Encoding.UTF8, "application/json")).Result;
Console.WriteLine((response.StatusCode.ToString()));
string resultContent = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultContent);
I guess I'm missing something in the header but can't find any information in the documentation about that.
It's a difficult issue so any advice will be very appreciated.
You shouldn't be including the HTTP header name ("Authorization: ") in the parameter of the AuthenticationHeaderValue. Setting the Authorization property will add the header to the request.
Additionally for OAuth 2, you probably want to be using "Bearer" as the scheme and not encoding token with base64.
Something like this should therefore work:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);