Wordnik authentication errors - c#

I'm attempting to retrieve an authentication token from Wordnik by using the provided API. However, I cannot seem to get it to work; I seem to be stuck getting 401 and 403 errors.
The following is the code I am using to request authentication from the API:
string authRequest =
String.Format("http://api.wordnik.com//v4/account.json/authenticate/{0}",
this.userName);
HttpWebRequest request = WebRequest.Create(authRequest) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
// When this is added, I get 403 errors
///request.Headers.Add("api_key", APIKey);
string postData = "password=" + password;
byte[] encodedData = UTF8Encoding.UTF8.GetBytes(postData);
request.ContentLength = encodedData.Length;
Stream stream = request.GetRequestStream();
stream.Write(encodedData, 0, encodedData.Length);
stream.Close();
string responseText;
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using(StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseText = reader.ReadToEnd();
Console.WriteLine(responseText);
Console.ReadLine();
}
}
Can any of you tell me what I'm doing incorrectly?
Any input is appreciated.

You have a double slash in the request URL:
"http://api.wordnik.com//v4"

Related

Bad Request(400) is alsways returned when I try to get access token from live.com

I already got the authorization code.
I try to get access token with the following code:
string requestUrl = "https://login.live.com/oauth20_token.srf";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string fields = string.Format("client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code", clientId_, "https://login.live.com/oauth20_desktop.srf", clientSecret_, authorizationCode_);
var data = Encoding.ASCII.GetBytes(fields);
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
The last string always raises an WebException: Bad Request
Update: Just remove client_secret from fields and get the access token:
string fields = string.Format("client_id={0}&redirect_uri={1}&code={2}&grant_type=authorization_code", clientId_, "https://login.live.com/oauth20_desktop.srf", authorizationCode_);

C# - Request Json File with authorization key (cURL example)

I'm trying to do a HTTP GET request for a json file from an api in a C# application. I'm having trouble getting the authorization, request headers and the webresponse (.GetResponse not working).
The example on the api's site is in curl.
curl -H "Authorization: Bearer ACCESS_TOKEN" https://erikberg.com/nba/boxscore/20120621-oklahoma-city-thunder-at-miami-heat.json
Here is my request method, which will also include JSON deseralization
public static string HttpGet(string URI)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URI);
// Not sure if the credentials input is the correct
string cred = $"{"Bearer"} {"ACCESS_TOKEN_IS_A_GUID"}";
req.Headers[HttpRequestHeader.Authorization] = cred;
req.Method = "GET";
// GetResponse() is "red", won't work.
WebResponse response = req.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd().Trim();
}
}
EDIT It was resolved. The problem was that the request was for a GZIP file and that had to be decompressed
var request = (HttpWebRequest)WebRequest.Create(requestUri);
request.UserAgent = userAgent;
request.ContentType = "application/json";
request.Method = WebRequestMethods.Http.Get;
request.Headers[HttpRequestHeader.Authorization] = bearer;
request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
var response = (HttpWebResponse) request.GetResponse();
string jsonString;
using (var decompress = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (var sr = new StreamReader(decompress))
jsonString = sr.ReadToEnd().Trim();
}
_Game = JsonConvert.DeserializeObject<Game>(jsonString);
You are not getting it because you don't have access.
The cURL command from API's site(that you mentioned in your question) gives the following JSON
{
"error" : {
"code" : "401",
"description" : "Invalid access token: ACCESS_TOKEN"
}
}
And so does the following code:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("URL");
req.UserAgent = "Bearer";
WebResponse response = req.GetResponse();
So what you need is a valid username/password or userAgent. You might want to contact the site for that.

scrape site after login

I'm trying to scrape a website that requires a login. Getting an error that I haven't received before, copied the code from another forum successfully in the past:
Exception Details: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
with the code:
Stream newStream = http.GetRequestStream(); //open connection
Here's the entire code:
#{
var strUserId = "userName";
var strPassword = "password";
var url = "formSubmitLandingSite";
var url2 = "pageToScrape";
HttpWebRequest http = WebRequest.Create(url) as HttpWebRequest;
http.KeepAlive = true;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
string postData = "email=" + strUserId + "&password=" + strPassword;
byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (Stream postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
HttpWebResponse httpResponse = http.GetResponse() as HttpWebResponse;
// Probably want to inspect the http.Headers here first
http = WebRequest.Create(url2) as HttpWebRequest;
http.CookieContainer = new CookieContainer();
http.CookieContainer.Add(httpResponse.Cookies);
HttpWebResponse httpResponse2 = http.GetResponse() as HttpWebResponse;
Stream newStream = http.GetRequestStream(); //open connection
newStream.Write(dataBytes, 0, dataBytes.Length); // Send the data.
newStream.Close();
string sourceCode;
HttpWebResponse getResponse = (HttpWebResponse)http.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
sourceCode = sr.ReadToEnd();
}
Response.Write(sourceCode);
}
You're creating a new request object here:
http = WebRequest.Create(url2) as HttpWebRequest;
Keep in mind that the default HTTP verb used is GET. Then you try to open the request stream here:
Stream newStream = http.GetRequestStream();
This method is used to enable writing data to the request's content. However, GET requests don't have content. As you do in the code above the error, you'll need to use a different HTTP verb. POST is most common for this, and is what you're using above:
http.Method = "POST";
So just use a POST request again. (Assuming, of course, that's what the server is expecting. In any event, if the server is expecting content then it's definitely not expecting a GET request.)

Getting a 401 error when submitting my datapayload to urbanairship

I'm trying to send a test notification to my ipod via UrbanAirship with C#. I've tried many code snippets trying to send my notification to UrbanAirship from my Windows server, yet I always end up with a 401 error.
Here's my latest code:
string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\""+ devToken +"\"]}";
var uri = new Uri("https://go.urbanairship.com/api/push/");
var encoding = new UTF8Encoding();
var request = (HttpWebRequest)WebRequest.Create(uri);
char[] charArray = Encoding.UTF8.GetChars(Encoding.UTF8.GetBytes(postData));
request.Method = "POST";
request.Credentials = new NetworkCredential(username, password);
request.ContentType = "application/json";
request.ContentLength = encoding.GetByteCount(charArray);
using (var stream = request.GetRequestStream())
{
stream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
stream.Close();
var response = request.GetResponse();
response.Close();
}
Note: I've verified that my username and password are correct.
===UPDATE===
I would say that there's something woring with my urbanairship config or so but the following worked:
curl -X PUT -u "appKey:appSecret" -H "Content-Type: application/json" --data '{"alias": "myalias"}' https://go.urbanairship.com/api/device_tokens/myTOken/
Fixed, I've modified my code and most important: YOUR PASSWORD IS THE APPLICATION MASTER SECRET
string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\""+ devToken +"\"]}";
var uri = new Uri("https://go.urbanairship.com/api/push/");
var encoding = new UTF8Encoding();
var request = (HttpWebRequest)WebRequest.Create(uri);
char[] charArray = Encoding.UTF8.GetChars(Encoding.UTF8.GetBytes(postData));
request.Method = "POST";
request.Credentials = new NetworkCredential(username, password);
request.ContentType = "application/json";
request.ContentLength = encoding.GetByteCount(charArray);
using (var stream = request.GetRequestStream())
{
stream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
stream.Close();
var response = request.GetResponse();
response.Close();
}

Programmatically login to google app engine c#

I've tried to login to my google app engine application from ASP.NET for a few days, but no luck. I've read the following articles and got the basic ideas. But nothing works for me.
http://code.activestate.com/recipes/577217-routines-for-programmatically-authenticating-with-/
http://dalelane.co.uk/blog/?p=303
http://dalelane.co.uk/blog/?p=894
http://krasserm.blogspot.com/2010/01/accessing-security-enabled-google-app.html
http://blog.notdot.net/2010/05/Authenticating-against-App-Engine-from-an-Android-app
I know what to do. 1) Get an auth token from ClientLogin. 2) Get a cookie from Google App Engine. 3) Post data to my app with the cookie (Yes, I want to post data, not redirect after the second part). But the third part doesn't work for me at all. It give me 403 error. Here is my code:
void PostToGAE()
{
var auth = GetAuth(); // I can get the authtoken
var cookies = GetCookies(auth); // I can get the ACSID cookie
var url = string.Format("http://test.appspot.com/do/something/");
var content = "testvalue=test";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.CookieContainer = cookies;
byte[] byteArray = Encoding.UTF8.GetBytes(content);
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // This gives me 403
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
reader.Close();
}
CookieContainer GetCookies(string auth)
{
CookieContainer cookies = new CookieContainer();
var url = string.Format("http://test.appspot.com/_ah/login?auth={0}",
System.Web.HttpUtility.UrlEncode(auth));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
request.CookieContainer = cookies;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
reader.Close();
return cookies;
}
string GetAuth()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/accounts/ClientLogin");
var content = "Email=test#gmail.com&Passwd=testpass&service=ah&accountType=HOSTED_OR_GOOGLE";
byte[] byteArray = Encoding.UTF8.GetBytes(content);
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string loginStuff = reader.ReadToEnd();
reader.Close();
var auth = loginStuff.Substring(loginStuff.IndexOf("Auth")).Replace("Auth=", "").TrimEnd('\n');
return auth;
}
My app.yaml looks like this:
- url: /do/something/
script: something.py
login: admin
If I change the method POST to GET, that works. Could anyone tell me how I can post data?
Thanks.
EDITED:
Still no luck. I've tried several ways such as changing to [login: required] in app.yaml, adding [secure: always] to app.yaml and changing the request protocol to https, appending continue parameter to /_ah/login, but all of them don't work :(
I totally have no idea why POST doesn't work at all but GET. Any ideas?
I made it. I was on the wrong track. That was not the problem of app engine but Django. I am using Django-nonrel on google app engine, and I totally forgot to put #csrf_exempt decorator to my handler. I had the same problem before, but again. Anyway, the code above has been apparently working correctly since at the beginning. What a smart boy :)

Categories

Resources