I am trying to call a locally hosted WCF REST service over HTTPS with basic auth.
This works and the Authorization header comes thru just fine and all is happy:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var request = (HttpWebRequest)WebRequest.Create("https://localhost/MyService/MyService.svc/");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add(
System.Net.HttpRequestHeader.Authorization,
"Basic " + this.EncodeBasicAuthenticationCredentials("UserA", "123"));
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
}
}
}
When I try to use RestSharp however, the Authorization header never comes thru on the request:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var credentials = this.EncodeBasicAuthenticationCredentials("UserA", "123");
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
var restRq = new RestSharp.RestRequest("/");
restRq.Method = Method.GET;
restRq.RootElement = "/";
restRq.AddHeader("Authorization", "Basic " + credentials);
var restRs = client.Execute(restRq);
What am i doing wrong with the RestSharp method?
I know that the AddHeader method works because this:
restRq.AddHeader("Rum", "And Coke");
will come thru, only "Authorization" seems stripped out/missing.
instead of adding the header 'manually' do the following:
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
client.Authenticator = new HttpBasicAuthenticator("UserA", "123");
I used milano's answer to get my REST service call to work (using GET)
Dim client2 As RestClient = New RestClient("https://api.clever.com")
Dim request2 As RestRequest = New RestRequest("me", Method.GET)
request2.AddParameter("Authorization", "Bearer " & j.access_token, ParameterType.HttpHeader)
Dim response2 As IRestResponse = client2.Execute(request2)
Response.Write("** " & response2.StatusCode & "|" & response2.Content & " **")
The key was making sure there was a space after the word 'Bearer' but this may apply to any type of custom token authorization header
You have to use ParameterType.HttpHeader parameter:
request.AddParameter("Authorization", "data", ParameterType.HttpHeader);
I was able to get the response from my rest API using this piece of code:
My API was returning server error and I used:
request.AddHeader("Authorization", $"Bearer {accessToken}");
var request = new RestRequest("/antiforgerytokensso", Method.Get);
restClient.Authenticator = new JwtAuthenticator(accessToken);
var response = await restClient.ExecuteAsync(request);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
Related
I have an API that is secured with username and password. I'm using ASP.NET Core MVC but I'm reading the API using JavaScript. Now my organization secured this API with username and password and I want to know how can I read the API with these username and password using C# because it's more secure than JavaScript. What code I can Add in my Post request in the controller. If you can guide me to a way to achieve this.
I found this way but it's not supported in ASP.NET Core:
WebRequest req = WebRequest.Create(#"https://sub.domain.com/api/operations?param=value¶m2=value");
req.Method = "GET";
req.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
//req.Credentials = new NetworkCredential("username", "password");
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
for net core it is better to use http client
using (var client = new HttpClient())
{
var baseAddress = "https://sub.domain.com";
var api = "/api/operations?param=value¶m2=value";
client.BaseAddress = new Uri(baseAddress);
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
var authenticationString = $"{username}:{password}";
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationString));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);
var response = await client.GetAsync(api);
var statusCode = response.StatusCode.ToString();
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<object>(stringData);
}
}
UPDATE
If you wont to use http client but use ajax too, just create an action with the code above and call this action from ajax.
how can get message from mail.tm
i have api can create email and can get token to sign in in website but when make api to get message it didn't get
HttpWebRequest hwq = (HttpWebRequest)WebRequest.Create("https://api.mail.tm/messages?page=1");
hwq.Method = "GET";
hwq.Accept = "application/ld+json";
hwq.Headers.Add(HttpRequestHeader.Authorization, "Bearer "+"Token");
var res = hwq.GetResponse();
using (var sr = new StreamReader(res.GetResponseStream()))
{
dynamic dd = JsonConvert.DeserializeObject(sr.ReadToEnd());
}
it run but get empty like it
{{"#context": "/contexts/Message","#id": "/messages", "#type": "hydra:Collection","hydra:member": [],"hydra:totalItems": 0}}
this code run in first code i send header "Bearer" then Token but i must send header like "Bearer " + "Token"
i must send it with space after "Bearer" then Token
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest hwq = (HttpWebRequest)WebRequest.Create("https://api.mail.tm/messages?page=1");
hwq.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + "Token");
hwq.Method = "GET";
hwq.Accept = "application/json";
var res = hwq.GetResponse();
using (var sr = new StreamReader(res.GetResponseStream()))
{
string a1 = sr.ReadToEnd();
}
After many struggles, I was finally able to get the OAuth Authentication/Refresh token process down. I am certain that the tokens I am using in this process are good. But I am struggling to communicate with the Compliance API and I think it may have more to do with my headers authentication process than it does specifically the Compliance API but I am not certain. I've tried so many different combinations of the below code unsuccessfully. I've tried to do the call as a GET and a POST (the call should be a GET). I've tried it with the access token encoded and not encoded. With all of my different code combinations tried I've been getting either an authorization error or a bad request error. You can see some of the various things I've tried from commented out code. Thank you for your help.
public static string Complaince_GetViolations(string clientId, string ruName, string clientSecret, string accessToken, ILog log)
{
var clientString = clientId + ":" + clientSecret;
//byte[] clientEncode = Encoding.UTF8.GetBytes(clientString);
//var credentials = "Basic " + System.Convert.ToBase64String(clientEncode);
byte[] clientEncode = Encoding.UTF8.GetBytes(accessToken);
var credentials = "Bearer " + System.Convert.ToBase64String(clientEncode);
var codeEncoded = System.Web.HttpUtility.UrlEncode(accessToken);
HttpWebRequest request = WebRequest.Create("https://api.ebay.com/sell/compliance/v1/listing_violation?compliance_type=PRODUCT_ADOPTION")
as HttpWebRequest;
request.Method = "GET";
// request.ContentType = "application/x-www-form-urlencoded";
//request.Headers.Add(HttpRequestHeader.Authorization, credentials);
//request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + codeEncoded);
request.Headers.Add(HttpRequestHeader.Authorization, credentials);
//request.Headers.Add("Authorization", "Bearer " + codeEncoded);
request.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY-US");
log.Debug("starting request.GetRequestStream");
string result = "";
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream())) //FAILS HERE
{
result = streamReader.ReadToEnd();
}
//DO MORE STUFF BELOW
return "STUFF";
}
And I finally figured out a resolution to this problem. The HTML encoding of the entire bearer string was the issue. If anyone needs this in the future your welcome. =)
HttpWebRequest request = WebRequest.Create("https://api.ebay.com/sell/compliance/v1/listing_violation?compliance_type=PRODUCT_ADOPTION")
as HttpWebRequest;
request.Method = "GET";
request.Headers.Add(HttpRequestHeader.Authorization, System.Web.HttpUtility.HtmlEncode("Bearer " + accessToken));
request.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY-US");
log.Debug("starting request.GetRequestStream");
string result = null;
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
When trying to post to a web service as multipart/form-data with digest authentication. It is failing with the following error 'System.Net.CredentialCache' is not supported for property 'Credentials'.
Using the below code to send credentials:
HttpWebRequest httpWebRequest = WebRequest.Create(requestUrl) asHttpWebRequest;
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
string contentType = "multipart/form-data; boundary=" + formDataBoundary;
byte[] formData = GetMultipartFormData(parameters, formDataBoundary);
if (httpWebRequest == null)
{
thrownewNullReferenceException("request is not a http request");
}
// Set up the request properties.
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = contentType;
httpWebRequest.CookieContainer = newCookieContainer();
var credentialCache = newCredentialCache();
credentialCache.Add(
newUri("http://someurl.com"), // request url's host
"Digest", // authentication type
newNetworkCredential(username, password) // credentials
);
httpWebRequest.Credentials = credentialCache;
We changed the services to use post with application/json instead and that solved it.
var response = await httpClient.PostAsync(requestUrl, new
StringContent(jsonString, Encoding.UTF8, "application/json"));
I'm trying to make a request to the Square Connect api to list the payments. I'm receiving this error
"The remote server returned an error: (401) Unauthorized."
The api says
Open your favorite command-line application (such as Terminal if you're using a Mac) and run the following curl command, providing your access token where indicated:
curl -H "Authorization: Bearer PERSONAL_ACCESS_TOKEN" https://connect.squareup.com/v1/me/payments
Here is my code. What am I doing wrong?
WebRequest request = WebRequest.Create("https://connect.squareup.com/v1/me/payments");
request.ContentType = "application/json";
request.Method = "GET";
request.Headers("Authorization") = "XXXXX";
HttpWebResponse response = null;
string responseMessage = null;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
using (Stream stream = response.GetResponseStream()) {
using (StreamReader reader = new StreamReader(stream)) {
responseMessage = reader.ReadToEnd();
}
}
}
Assert.IsNotNull(responseMessage);
var client = new RestSharp.RestClient();
var request = new RestRequest("https://connect.squareup.com/v1/me/payments", Method.GET);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Bearer xxxxx");
//setHeaders(request);
var Response = client.Execute(request);
Instead of
request.Headers("Authorization") = "XXXXX";
Do this
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + yourPersonalAccessToken);