I'm trying to use an outside REST api that was recently developed by an outside company. They provided me with some Java code to show how to connect to it and retrieve data, but so far I'm having no luck getting any results with C# MVC 4. Currently I cannot even login to the system. The credentials are correct, and using examples that I've found elsewhere don't seem to help.
The Java code that works:
try{
ClientConfig client_config = new ClientConfig();
client_config.register(new HttpBasicAuthFilter(username,password));
Client client = ClientBuilder.newClient(client_config);
WebTarget web_target = client.target(url);
Invocation.Builder invocation_builder = web_target.request();
//This GET does the login with basic auth
this.populateFromResponse(invocation_builder.get());
}
catch(final Exception e){
System.out.println(e.toString());
}
Ok, there are objects here that I don't have in C#, clearly, but everything I've tried has yet to work.
I have tried placing info in the header of the request:
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
No cookies, also tried:
request.Credentials = new NetworkCredential(username, password);
Nothing. If I try this, receive no cookies, and still attempt to access any other part of the api, then I get a 401(Not Authorized) error. The request.GetResponse(); doesn't throw an error if I'm simply trying to access the login section of the api.
I'm new to REST services, so any help/direction is appreciated. I'm only asking because everything else that I've looked up doesn't seem to work.
Edit
Here's how I'm building the request:
var request = (HttpWebRequest)WebRequest.Create(HostUrl + path);
request.Method = "GET";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
var response = request.GetResponse() as HttpWebResponse;
Edit #2
Thanks to #BrianP for his answer, which led me to solving this issue a little better. Below is my current code (along with additions to collect cookies from the response taken from this question) that finally returned a success code:
var cookies = new CookieContainer();
var handler = new HttpClientHandler();
handler.CookieContainer = cookies;
var client = new HttpClient(handler);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password)));
client.BaseAddress = new Uri(HostUrl);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(HostUrl + "/api/login/").Result;
var responseCookies = cookies.GetCookies(new Uri(HostUrl)).Cast<Cookie>()
Please let me know if there are improvements for this code. Thanks again!
public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
req.Headers["Authorization"] = "Basic " + authInfo;
}
Pulled from: http://blog.kowalczyk.info/article/at3/Forcing-basic-http-authentication-for-HttpWebReq.html
EDIT: Based on Comments.
HttpRequestMessage requestMsg = new HttpRequestMessage();
string data = username + ":" + password;
requestMsg.Headers.Authorization = new AuthenticationHeaderValue("Basic", data);
Related
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();
}
I'm trying to do a GET in an UWP (Windows 10) app. I've tried several ways but all always return 401.
In Postman it works fine, but I can' seem to get it to work in my app. What am I missing.
These are the methods I tried (all return 401):
Method 1:
var request = WebRequest.Create("http://api.fos.be/person/login.json?login=200100593&password=pass");
request.Headers["Authorization"] = "Basic MYAUTHTOKEN";
var response = await request.GetResponseAsync();
Method 2:
const string uri = "http://api.fos.be/person/login.json?login=200100593&password=pass";
var httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new System.Net.NetworkCredential("MYUSERNAME", "MYPASSWORD");
using (var client = new HttpClient(httpClientHandler))
{
var result = await client.GetAsync(uri);
Debug.WriteLine(result.Content);
}
Method 3:
var client = new RestClient("http://api.fos.be/person/login.json?login=200100593&password=pass");
var request = new RestRequest(Method.GET);
request.AddHeader("postman-token", "e2f84b21-05ed-2700-799e-295f5470c918");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Basic MYAUTHTOKEN");
IRestResponse response = await client.Execute(request);
Debug.WriteLine(response.Content);
The third method is code generated straight from Postman, so why is it working there and not in my app?
This thread helped me figure out the solution. I was using http:// but I had to make it https://. HTTPS with the code in that thread was the solution.
This is my final code:
public static async void GetPerson()
{
//System.Diagnostics.Debug.WriteLine("NetworkConnectivityLevel.InternetAccess: " + NetworkConnectivityLevel.InternetAccess);
//use this, for checking the network connectivity
System.Diagnostics.Debug.WriteLine("GetIsNetworkAvailable: " + System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable());
//var msg = new Windows.UI.Popups.MessageDialog("GetIsNetworkAvailable: " + System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable());
//msg.ShowAsync();
HttpClient httpClient = new HttpClient();
// Assign the authentication headers
httpClient.DefaultRequestHeaders.Authorization = CreateBasicHeader("MYUSERNAME", "MYPASS");
System.Diagnostics.Debug.WriteLine("httpClient.DefaultRequestHeaders.Authorization: " + httpClient.DefaultRequestHeaders.Authorization);
// Call out to the site
HttpResponseMessage response = await httpClient.GetAsync("https://api.fos.be/person/login.json?login=usern&password=pass");
System.Diagnostics.Debug.WriteLine("response: " + response);
string responseAsString = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine("response string:" + responseAsString);
}
public static AuthenticationHeaderValue CreateBasicHeader(string username, string password)
{
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(username + ":" + password);
String logindata = (username + ":" + password);
System.Diagnostics.Debug.WriteLine("AuthenticationHeaderValue: " + new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)));
return new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
}
I would try this first:
Check your "MYAUTHTOKEN", it is usually a combo of username:password and is base 64 encoded. So if your username was "user" and password was "pass" you would need to base64 encode "user:pass"
var request = WebRequest.Create("https://api.fos.be/person/login.json");
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Text.Encoding.UTF8.GetBytes("user:pass"));
var response = await request.GetResponseAsync();
i am connecting to a server with basic authentication and after that i am calling the URL in Webview with following code:
WebView.Source(new Uri("https:(//UrlHere"));
The Webview Puts up a Login-Window, but i am already logged in. Why is this happening?
How can i prevent this?
The way i a authenticate to the server:
private async void HttpClientCall(object sender, RoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine(this.GetType().Name + ": HTTPCLientCall entered");
//System.Diagnostics.Debug.WriteLine("NetworkConnectivityLevel.InternetAccess: " + NetworkConnectivityLevel.InternetAccess);
//use this, for checking the network connectivity
System.Diagnostics.Debug.WriteLine("GetIsNetworkAvailable: " + System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable());
//var msg = new Windows.UI.Popups.MessageDialog("GetIsNetworkAvailable: " + System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable());
//msg.ShowAsync();
HttpClient httpClient = new HttpClient();
// Assign the authentication headers
httpClient.DefaultRequestHeaders.Authorization = CreateBasicHeader("username", "password");
System.Diagnostics.Debug.WriteLine("httpClient.DefaultRequestHeaders.Authorization: " + httpClient.DefaultRequestHeaders.Authorization);
// Call out to the site
HttpResponseMessage response = await httpClient.GetAsync("https://URLHere");
System.Diagnostics.Debug.WriteLine("response: " + response);
string responseAsString = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine("response string:" + responseAsString);
//WebViewP.Source = new Uri("https://URLHere");
}
public AuthenticationHeaderValue CreateBasicHeader(string username, string password)
{
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(username + ":" + password);
String logindata = (username + ":" + password);
System.Diagnostics.Debug.WriteLine("AuthenticationHeaderValue: " + new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)));
return new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
}
So how can i solve that?
This is a long shot, but you could try setting the credentials on HttpClientHandler and hope that the WebView picks it up.
var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential(username,password);
HttpClient httpClient = new HttpClient(handler);
The problem is the WebView is making it's own independent request, so any requests you make with HttpClient are independent of those made by the WebView
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));
Here is the sample code for PHP Webservice client that works:
$options = array();
$options['trace'] = 1;
$options['login'] = 'username';
$options['password'] = 'password';
$client = new SoapClient("http://wsurl.com/pt/wsdl", $options);
I would like to access this webservice using c# but having a hard time doing the authentication. Do I need to explicitly set the soap headers or there is a built in way to send credentials in .NET
There are two ways to do this because servers handle authentication differently. First you could use something like this:
var req = WebRequest.Create(<your url>);
NetworkCredential creds = new NetworkCredential(<username>, <password>);
req.Credentials = creds;
var rep = req.GetResponse();
However if you need an actual Authroization header you will want to use this code
public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
req.Headers["Authorization"] = "Basic " + authInfo;
}
And then your request code becomes
var req = WebRequest.Create(<your url>);
SetBasicAuthHeader(req, username, password);
rep = req.GetResponse();
Let me know if you have any questions.
If you add a service reference in your C# project, you can just call your service like this:
var proxy = new YourServiceClient();
proxy.ClientCredentials.UserName.UserName = "username";
proxy.ClientCredentials.UserName.Password = "password";
More information can be found here: http://msdn.microsoft.com/en-us/library/ms733775.aspx.