I am (trying) to develop a WPF (C#) app that just gets (or at least is supposed to get) my saved bookmarks at Diigo.com profile. The only helpful page i found is this . It says i have to use HTTP Basic authetication to get my self authenticated and make requests then. But don't understand how C# handles it!. The only solution i came up with below just prints entire HTML source to console window.
string url = "http://www.diigo.com/sign-in";
WebRequest myReq = WebRequest.Create(url);
string usernamePassword = "<username>:<password>";
CedentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential("username", "password"));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
//Send and receive the response
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.Write(content);
Here username and password are hardcoded but of course they'll come from some txtUsername.Text thing. And after that how am i going to read the JSON response and parse it?
What is that i need to do to get my app or myself HTTP basic authenticated?
Any help or suggestion is welcome!
If you're trying to talk to a service, you probably want to use the Windows Communication Foundation (WCF). It's designed specifically to solve the problems associated with communicating with services, such as reading/writing XML and JSON, as well as negotiating transports mechanisms like HTTP.
Essentially, WCF will save you doing all of the "plumbing" work of working with HttpRequest objects and manipulating strings. Your problems have already been solved by this framework. Use it if you can.
Ok i solved the problem after some (not really some) effort. Code below gets the JSON response from server which can then be parsed using any preferred method.
string key = "diigo api key";
string username = "username";
string pass = "password";
string url = "https://secure.diigo.com/api/v2/";
string requestUrl = url + "bookmarks?key=" + key + "&user=" + username + "&count=5";
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(requestUrl);
string usernamePassword = username + ":" + pass;
myReq.Timeout = 20000;
myReq.UserAgent = "Sample VS2010";
//Use the CredentialCache so we can attach the authentication to the request
CredentialCache mycache = new CredentialCache();
//this perform Basic auth
mycache.Add(new Uri(requestUrl), "Basic", new NetworkCredential(username, pass));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
//Send and receive the response
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.Write(content);
content is the JSON response returned from server
Also this link is useful for getting started with api.
Related
I am trying to get list of orders from Woocommerce using Latest REST API v3. I am using Basic Authentication. It is said that Woocommerce Supports basic Authentication for Https (SSL enable).
My code is below .
WebRequest myReq = (HttpWebRequest)WebRequest.Create("https://shyamssaging.com:443/woocommerce/wc-api/v3/orders");
string usernamePassword = "ck_255fd4ab5dfb235065932b5ed72f419a8c2659e2:cs_7f619115423ff9d9b845fca8ee7053ff01c4ab27";
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(usernamePassword)));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Error is Unauthorized. Even, i am using valid Userkey and secret key .
Thanks
Shyams
There's a REST API Client Library you can find here , you'll need to make minor changes to the code.
Create a new class in your application called WoocommerceApiClient.cs and paste the code from the link above in it ( as I already mentioned you need to make minor changes )
You can then reference it using
string ConsumerKey = "key";
string ConsumerSecret = "secret";
string StoreUrl = "https://www.fishbowlstaging.com";
bool Isssl = true;
WoocommerceApiClient client = new WoocommerceApiClient(ConsumerKey, ConsumerSecret, StoreUrl, Isssl);
string orders = client.GetProducts();
You can add more methods to the class as you require.
I am developing ASP.net application which consumes REST services with ASP.Net Web API. I am trying to use Basic authentication for my website. I plan to use it with SSL once I complete Basic authentication.
Currently on Login button click I am sending Auth header using Base64 encoding of username and password as shown below:
string responseData = string.Empty;
string authToken = string.Empty;
string loginInstance = url;
// Create request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "POST";
request.ContentType = "application/json";
request.CookieContainer = new CookieContainer();
String username = txtUserName.Text;
String password = txtPassword.Text;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
request.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
String resultData = reader.ReadToEnd();
bool result = false;
result = Convert.ToBoolean(resultData);
return result;
I assume I will need to send authentication header to all of those web api requests that needs to be secure and pass through authentciation.
Is there a way to attach authentication header to every request that I send or even to a set of requests?
Please note: most of the Web API requests are invoked through JQuery.
Also please let me know if this is not recommended approach of implementation.
Regards,
Abhilash
Have you try like this :
WebRequest request = (HttpWebRequest)WebRequest.Create("https://yoururl");
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("user:password")));
basic http authentication in asp.net web api using message handlers.
http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-message-handlers/
Can you try with below code inplace of "request.Headers.Add("Authorization", "Basic " + encoded);" .
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " +
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("user:password")));
I believe you can just add
request.PreAuthenticare = true
You may look for HttpWebRequest.Credentials Property.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Credentials = CredentialCache.DefaultCredentials;
Above example contains the credentials of the currently logged on user.
"The Credentials property can be either a NetworkCredential, in which case the user, password, and domain information contained in the NetworkCredential object is used to authenticate the request, or it can be a CredentialCache".
MSDN Reference
I am completely new to REST API.
I would like to retrieve ListItems in xml format from an external site in C#.
I have got the username and password for the site (which uses Mixed authentication by the way).
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create("https://<site>/_api/web/lists");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/atom+xml";
//endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
endpointRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("<domain>\\<username>:<password>"));
HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
I am using this piece of code that I found on MSDN.
Would anybody please be kind enough to tell me how do I get an access token?
Why am I getting 403 Forbidden error?
I think you can better use the NetworkCredential class:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
NetworkCredential credentials = new NetworkCredential("testuser", "testpass");
request.Credentials = credentials;
No need to send the Authorization header
When I have to use REST API I use Tiny.RestClient 1
In your case you have to write the call like that :
var client = new TinyRestClient(new HttpClient(), "https://<site>/_api/");
client.GetRequest("web/lists")
Hopes that help.
WithBasicAuthentication("username", "password").
ExecuteAsync();
I would like to know why my asp.net application will not add the header to my post when it is named 'Authorization' but will work fine when I change one character, say "Authorizations". In documentation for other sites they always use the name "Authorization" so I would like to as well and at this point I just want to under stand why.
I have read a few topics about this but have not found any logical reason why.
Here is my code below:
string fileName = "c:\\xyz.xml";
string uri = "http://myserver/Default.aspx";
req = WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "text/xml";
byte[] authBytes = Encoding.UTF8.GetBytes("DDSServices:jCole2011".ToCharArray());
req.Headers.Add("Authorization", "BASIC " + Convert.ToBase64String(authBytes) );
req.Headers.Add("test", "test");
UTF8Encoding encoder = new UTF8Encoding();
byte[] data = encoder.GetBytes(this.GetTextFromXMLFile(fileName));
req.ContentLength = data.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
req.Headers.Add("Authorization", "BASIC" + Convert.ToBase64String(authBytes));
System.Net.WebResponse response = req.GetResponse();
System.IO.StreamReader reader = new StreamReader(response.GetResponseStream());
string str = reader.ReadToEnd();
The other annoying this is when i add the watched variable through fiddler it works fine.
I was ran into a question how to add Authentication/Credentials to the headers. I found the solution in the following way.
string _auth = string.Format("{0}:{1}", "myUser","myPwd");
string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth));
string _cred = string.Format("{0} {1}", "Basic", _enc);
req.Headers[HttpRequestHeader.Authorization] = _cred;
Which gave me those headers I want (pasted Wireshark descriptions),
Authorization: Basic bXlVc2VyOm15UHdk\r\n
Credentials: myUser:myPwd
For HTTP Basic Authorization, you should be using the Credentials property.
req.Credentials = new NetworkCredential("DDSServices", "jCole2011");
This should do what you want. Rather than setting the Authorization header.
NetworkCredential is a good solution but the site you are calling has to handle an unauthorized with a 401 AND a WWW-Authenticate header in the response.
Client:
request.Credentials = new CredentialCache {{aUri, "Basic", new NetworkCredential(aUserName, aPassword)}};
Server:
Response.ClearContent();
Response.StatusCode = 401;
Response.AddHeader("WWW-Authenticate", "Basic");
Response.End();
This will result in 2 hits to the server. The initial call will go to the server without credentials. When the server responds with a 401 AND the WWW-Authenticate header (with the type of authentication required), the request will be resent with the credentials in the request.
I want to request reports from a third party and they require "Basic Access Authentication" via POST:
Your client application must use Basic Access Authentication
to send the user name and password.
Can someone point me in the right direction?
Edit: I did see this post but there are two answers and I'm not sure if thats what I need to do or which one is the preferred method.
Assuming you use a WebRequest, you attach a CredentialCache to your request:
NetworkCredential nc = new NetworkCredential("user", "password");
CredentialCache cc = new CredentialCache();
cc.Add("www.site.com", 443, "Basic", nc);
WebRequest request = WebRequest.Create("https://www.site.com");
request.Credentials = cc;
request.PreAuthenticate = true;
request.Method = "POST";
// fill in other request properties here, like content
WebResponse respose = request.GetResponse();
The basic gist is like this:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = WebRequestMethods.Http.Get;
request.Credentials = new NetworkCredential(username, password);
but sometimes there are issues with using request credentials, the alternative is add the authentication data in request headers
string authInfo = username + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
for more details see this blog post
http://charlie.cu.cc/2012/05/how-use-basic-http-authentication-c-web-request/