Subscribe through API .net C# - c#

I have to submit subscription data to another website. I have got documentation on how to use this API however i'm not 100% sure of how to set this up. I do have all the information needed, like username / passwords etc.
This is the API documentation:
https://www.apiemail.net/api/documentation/?SID=4
How would my request / post / whatever look like in C# .net (vs 2008) when i'm trying to acces this API?
This is what i have now, I think i'm not on the right track:
public static string GArequestResponseHelper(string url, string token, string username, string password)
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Headers.Add("Username: " + username);
myRequest.Headers.Add("Password: " + password);
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
Stream responseBody = myResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(responseBody, encode);
//return string itself (easier to work with)
return readStream.ReadToEnd();
Hope someone knows how to set this up properly. Thx!

The documentation doesn't state clearly if the credentials should be passed as HTTP headers. They talk about parameters, so I would also try passing them as GET parameters:
url = string.Format("{0}?Username={1}&Password={2}", url, username, password);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);

Related

I want to get Stex.com API access token

I am developing C# WinForms application to trade on Stex.com.
They upgraded their api to api3.
It uses google authentication app to login.
That's why there's no way to get access token without man's behavior.
Finally, I determined to use postman to get access token and I want to refresh token when the token is expired.
I think it the best way.
So I got the access token and refresh token via postman.
https://help.stex.com/en/articles/2740368-how-to-connect-to-the-stex-api-v3-using-postman .
now it's the turn to refresh my token.
so this is what I wrote.
string refresh_token = "def50200b03974080...";
string client_id = "502";
string client_secret = "SeTs50aFxV1RoMFBW1b4RVNQhh2wEdICaYQrpE3s";
string AccessToken = "eyJ0eXAiOiJKV1QiLCJhbGciO...";
string url = #"https://api3.stex.com/oauth/token";
var request = HttpWebRequest.Create(url);
request.Method = "POST";
request.Headers.Add("Authorization", "Bearer " + AccessToken);
request.ContentType = "application/x-www-form-urlencoded";
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("grant_type", "refresh_token");
outgoingQueryString.Add("refresh_token", refresh_token);
outgoingQueryString.Add("client_id", client_id);
outgoingQueryString.Add("client_secret", client_secret);
outgoingQueryString.Add("scope", "trade profile reports");
outgoingQueryString.Add("redirect_uri", #"https://www.getpostman.com/oauth2/callback");
byte[] postBytes = new ASCIIEncoding().GetBytes(outgoingQueryString.ToString());
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Flush();
postStream.Close();
using (WebResponse response = request.GetResponse())
{
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
dynamic jsonResponseText = streamReader.ReadToEnd();
}
}
It shows 401(Unauthorized) error.
And when I remove ContentType, it shows 400(Bad Request) error.
If anyone did this, please help me.
guys!
Finally, I found the issue.
The issue was due to my ignorance.
Calm down and have a relax when you get issue.
:)
I created 2 api3 clients and so client_secret was different.
Thank you.

How to send authentication header in ASP.Net for set of web request

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

Logging into a website via C#, navigating to another web page, and then output the source code as a string

I am relatively new to working with web pages in C#. What I am trying to do is log into a particular website ( https://www15.swalife.com/PortalWeb/portal/cwaLogon.jsp ) and allowing the page to be redirected to the default page, and then navigating from there to (https://www15.swalife.com/csswa/ea/plt/accessELITT.do) and downloading the source code and output it to a string.
I have figured out how to download the source code via HTTPWebRequest and HTTPWebResponse but am having trouble on coding the logging in function. I assume I will have to do something with POST? I have looked at http://www.dreamincode.net/forums/topic/152297-c%23-log-in-to-website-programmatically/ also.
Thanks in advance!!
EDIT:
The code supplied by jimmyjambles works flawlessly, except it doesn't quite get me the source code of the page I wanted. The code suggests that the log-in process failed, but I believe with a little bit of tweaking I could get it to work...also to everyone having issues with:
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(AcceptAllCertifications);
Try changing your "public string" and "public bool" functions to "public static string" and "public static bool" respectively :)
EDIT 2:
Response HTML:
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<HTML>\n<HEAD>\n\n\n\n\n\n\n<META http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\n<META name=\"GENERATOR\" content=\"IBM WebSphere Studio\">\n<TITLE>endSession.jsp</TITLE>\n<LINK rel=\"stylesheet\" href=\"eipPortletStyles/swalife.css\" type=\"text/css\">\n\t<script type=\"text/javascript\" language=\"JavaScript\" \n\t\tsrc=\"eipCommonJavaScript/eipGeneralFunctions.js\"/> </script>\n\t\t\n<script type=\"text/javascript\">\n\n\tfunction refreshParent()\n\t{\n\t if(window.parent)\n\t {\n\t if(window.parent.name == 'appMainFrame')\n\t window.parent.location = \"/csswa/ea/plt/logout.do\";\n\t // alert('Your session has expired. Please login again. ');\n\t }\n\t}\n\n</script>\n</HEAD>\n<BODY onload=\"refreshParent();\">\n \n\t \t<div class=\"eipErrors\">\n \t\t\t<div class=\"legendLabel\">Message</div>\n \t\t\t\n \t\t\t <div class=\"errorsHeader formTitle\">You Have Exited Out of Crew Web Access.<br> \t\t\t \n \t\t\t </div>\n \t\t\t \n \t\t\t<div class=\"errorsHeader formTitle\"> Please Close this Window and <font size=\"+1\">Log Out of SWALife</font> to Complete the Log Out Process. </div>\n \t\t<div class=\"errorsText\">\n \t\t \n \t\t\t\t\n \t\t</div>\n \t\t\n \t\t\t\n \t\t\n \t\t<div class=\"errorsFooter\">You will need to log back in before continuing.</div> \t\n \t\t\n \t</div>\n \n</BODY>\n</HTML>\n"
In order to use HttpWebRequest to access a secondary URL after login you will need to keep in mind a few things.
Firstly as Casperah has mentioned you will need to inspect the login form and identify the "name" attribute of the controls used to receive the login data.
Once you have done this you will need to format a post string accordingly and provide it to the WebRequest.
The last consideration is that once you have logged in, you will need to store and maintain the cookie assigned to you from the server that keeps you logged in.
I have taken a WebRequest snippet from this msdn article and modified it to perform a second page request after the login.
string loginurl = "http://www.gmail.com";
string secondurl = "http://mail.google.com/prefs";
string username = "bob#gmail.com";
string password = "12345";
GetSecondaryLoginPage(loginurl, secondurl, username, password);
public string GetSecondaryLoginPage(string loginurl, string secondurl, string username, string password, string cookieName = null)
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginurl);
// Set the Method property of the request to POST.
request.Method = "POST";
CookieContainer container = new CookieContainer();
if (cookieName != null)
container.Add(new Cookie(cookieName, username, "/", new Uri(loginurl).Host));
request.CookieContainer = container;
// Create POST data and convert it to a byte array. Modify this line accordingly
string postData = String.Format("username={0}&password={1}", username, password);
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
using (StreamWriter outfile =
new StreamWriter("output.html"))
{
outfile.Write(responseFromServer.ToString());
}
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
request = (HttpWebRequest)WebRequest.Create(secondurl);
request.CookieContainer = container;
response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream);
// Read the content.
responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
The only added lines are for the postData and cookies.
You will need to modify the line
string postData = String.Format("username={0}&password={1}", username, password);
based on your controls on the form, since you posted the site your trying to work with I can guess that you are probably looking for
string postData = String.Format("uid={0}&portalBase=cwa&password={1}", username, password);
Using a WebBrowser in a form is fairly easy. Start by navigating to the cwaLogon.jsp page and locate the input-controls and Invoke "click" on the submit button.
Either that or make the appropriate GET/POSTs using HTTPWebRequest and Response.
Using Fiddler2 to check what to post is a great start.

HTTP Basic Auth for Diigo using C#: How to read response?

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.

How to migrate to Google OAuth from AuthSub?

I have an existing application that displays Google Analytics data. Currently, it stores the username and password which I do not like, so I wanted to convert it to use OAuth. I have isolated the authentication method to get the token in hopes that all I would have to do is change this method:
public static string getSessionTokenClientLogin(string email, string password)
{
//Google analytics requires certain variables to be POSTed
string postData = "Email=" + email + "&Passwd=" + password;
//defined - should not channge much
postData = postData + "&accountType=HOSTED_OR_GOOGLE" + "&service=analytics" + "&source=testcomp-testapp-1";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://www.google.com/accounts/ClientLogin");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
Stream responseBody = myResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(responseBody, encode);
//returned from Google Analytics API
string response = readStream.ReadToEnd();
//get the data we need
string[] auth = response.Split(new string[] { "Auth=" }, StringSplitOptions.None);
//return it (the authorization token)
return auth[1];
}
Is there an easy way to convert this to OAuth? I can change the parameters, but I am hoping I do not have to make architectural changes to the rest of my app. Thanks!
You should be able to use the guide found at http://blog.stevienova.com/2008/04/19/oauth-getting-started-with-oauth-in-c-net/ as a basis for writing code to grab an OAuth token. You should use https://www.google.com/accounts/OAuthGetRequestToken (as indicated here) instead of http://term.ie/oauth/example/request_token.php , obviously. I don't think you will need to substantially change your architecture to get this working. Also, you will need to authorize the token before you can use it. I think reading through http://code.google.com/apis/accounts/docs/OAuth_ref.html should get you most of what you need.

Categories