I use Restsharp for a WPF client that I'm developing.
It appears that I receive no cookies in the client.CookieContainer where it has always 0 items after I successfully authenticate to our server.
It's weird because the same request is sent with Postman and I receive a JSESSIONID cookie that is not present when the request is sent with Restsharp.
public static async Task<IRestResponse> SendLogonRequest(string UID, SecureString pwd)
{
var restClient = new RestClient(new Uri(URLSRV))
{
Authenticator = new HttpBasicAuthenticator(UID, pwd.ToInsecureString()) //base64 auth;
};
restClient.CookieContainer = new CookieContainer();
var restRequest = new RestRequest(Method.POST);
restRequest.AddHeader("Accept", "application/json");
restRequest.AddHeader("Content-Type", "application/json");
var cancellationTokenSource = new CancellationTokenSource();
var restResponse = await restClient.ExecuteTaskAsync(restRequest, cancellationTokenSource.Token);
return restResponse;
}
I've seen on a post that if the cookie has a HttpOnly flag it will not work. (see: https://stackoverflow.com/a/21072840/7031019)
this doesn't help me because I can't change anything from server side.
Thank you
Related
Basically, I've been trying to authenticate through oauth2 on c# using restsharp, but I am receiving a bad request response, I'm not sure if it's something related to the API configuration or if it's something I'm missing In my code.
public string getToken(string email, string password)
{
var restclient = new RestClient(loginUrl);
RestRequest request = new RestRequest("request/oauth") { Method = Method.GET };
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("email", HttpUtility.UrlPathEncode(email));
request.AddParameter("password", HttpUtility.UrlPathEncode(password));
request.AddParameter("grant_type", HttpUtility.UrlPathEncode("password"));
var tResponse = restclient.Execute(request);
var responseJson = tResponse.Content;
string token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
return token;
}
this is the response when I execute that code
An this is the postman execution
Thanks!
I think there problem with adding parameters the way you are adding.
latest restsharp support this,
Also,avoid encoding of params by setting to false
var request = new RestRequest("resource", Method.GET);
request.AddQueryParameter("email", "test#test.com",false);
var restclient = new RestClient(loginUrl); I think you need to check your url.
Try this.. you OAuth is password grantype are your sure your not missing any credentials like client_id, scope and client_secret.
public static string getAccessToken(string usern, string pswd)
{
RestClient client = new RestClient(ConfigurationManager.AppSettings["TokenUrl"]);
RestRequest request = new RestRequest() { Method = Method.GET};
request.AddParameter("grant_type", "password", ParameterType.GetOrPost);
request.AddParameter("username", usern, ParameterType.GetOrPost);
request.AddParameter("password", pswd, ParameterType.GetOrPost);
IRestResponse response = client.Execute(request);
var responseJson = response.Content;
var token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
return token;
}
I am using RestSharp to make a GET api call. The api call is authenticated through HTTP Basic authentication by passing the authorization header.
The server redirects the api call with a status code 307. My client code does handle the redirects but the authorization header is not passed to this redirected api call. This is done for valid reasons as mentioned here. Hence I do get an unauthorized error.
How can I configure the RestClient to restore the authorization header?
var client = new RestClient("https://serverurl.com");
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Basic Z3JvdXAxOlByb2otMzI1");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Tenant-Id", "4892");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
I added a check that resends the api request of receiving a 401 with the below code.
var client = new RestClient("https://serverurl.com");
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Basic Z3JvdXAxOlByb2otMzI1");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Tenant-Id", "4892");
IRestResponse response = client.Execute(request);
//Resend the request if we get 401
int numericStatusCode = (int)response.StatusCode;
if(numericStatusCode == 401) {
var redirectedClient = new RestClient(response.ResponseUri.ToString());
IRestResponse newResponse = redirectedClient.Execute(request);
Console.WriteLine(newResponse.ResponseStatus);
}
I am working with the Basecamp API which is a REST (JSON) API using basic HTTP authentication over HTTPS.
This should be a GET request but when I run my code using GET I am receiving:
Cannot send a content-body with this verb-type
When I run it as a POST, I receive:
{"status":"400","error":"Bad Request"}
Does anyone know why this may be occurring?
using (var httpClient = new HttpClient()) {
string userName = "someone#someone.com";
string password = "somepassword";
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, password)));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://correctUrlHere);
requestMessage.Headers.Add("User-Agent", "TheProject (someone#someone.com)");
requestMessage.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(requestMessage);
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
In this code I obviously swapped out the username, password, project name, and URL but in the actual code they are all correct.
GET requests must pass their parameters as url query and not as request body.
http://example.com?p1=1&p2=helloworld
If you don't have any content, as your example suggests, omit setting it on the request.
The BadRequest result indicates some error with your payload (again: content seems to be empty).
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);
I am trying to do the following using .NET
What would the C# code look like using HttpClient, if my username is test and password is password?
HTTP Method: GET
URL: http://webapi.ebayclassifieds.com/webapi/categories
Sample command:
curl --digest -u{username}:{password} http://webapi.ebayclassifieds.com/webapi/categories
Here is what I have but I don't get the html:
var client = new HttpClient();
var requestContent = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("-u", "{test}:{password}") });
HttpResponseMessage response = await client.PostAsync(
"http://webapi.ebayclassifieds.com/webapi/categories", requestContent);
// Get the response content.
HttpContent responseContent = response.Content;
var blah = response.Content.ReadAsStringAsync();
Try this one:
CredentialCache credCache = new CredentialCache();
credCache.Add (new Uri ("http://webapi.ebayclassifieds.com"), "Digest", new NetworkCredential ("username", "passwd"));
After that construct the HttpClient with the credential cache:
var httpClient = new HttpClient( new HttpClientHandler { Credentials = credCache});
Rest of the process is same. If you perform http POST then use PostAsync, and for http GET use GetAsync.
You'll find more detail about CredentialCache from here.