Eventbrite OAUTH2 login on windows store apps keep me get BAD REQUEST - windows-8

I got problem on oauth2 handshake, as the eventbrite documentation is not very clear.
http://developer.eventbrite.com/doc/authentication/oauth2/ -> number 4
what i currently do is like this
WebRequest webRequest = WebRequest.Create("https://www.eventbrite.com/oauth/token");
string URLEncoded = "code=" + token + "&client_secret=" + APISecret + "&client_id=" + APIKey + "&grant_type=authorization_code";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(URLEncoded);
Stream os = null;
try
{
os = await webRequest.GetRequestStreamAsync();
os.Write(bytes, 0, bytes.Length);
WebResponse response = await webRequest.GetResponseAsync();
os = response.GetResponseStream();
StreamReader reader = new StreamReader(os);
string responseFromServer = reader.ReadToEnd();
}
catch (WebException ex)
{
string err = ex.ToString();
}
finally
{
if (os != null)
{
os.Dispose();
}
}
Can someone give tips on this? i keep getting BAD REQUEST as a result. Thank you
edited : the response say : code is invalid or expired
I know its clear, but i already implement and get the token to exchange, use Secret API key and API Key to get it, but how come its invalid/expired?

Related

Weird response from API at Litecoin exchange

I'm trying to send a POST request to the Livecoin API. I have ensured that every parameter and the encoding is correct, but I keep getting a weird response:
{"success":false,"exception": "Unknown currency pair [currencyPair={1}]|null"}
This is what I'm trying to post:
string response = PrivatePostQuery("exchange/buymarket", "currencyPair=BTC/USD&price=12&amount=12");
And this is the method:
public string PrivatePostQuery(string requestUrl, string parameters = "")
{
parameters = http_build_query(parameters);
string Sign = HashHMAC(this.Exchange.ExchangeConnection.ApiSecretKey, parameters).ToUpper();
string uri = this.Exchange.ExchangeConnection.ApiUrl + requestUrl + "?" + parameters;
byte[] bytes = Encoding.UTF8.GetBytes(parameters);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
request.Headers["Api-Key"] = this.Exchange.ExchangeConnection.ApiKey;
request.Headers["Sign"] = Sign;
Stream dataStream = request.GetRequestStream();
dataStream.Write(bytes, 0, bytes.Length);
try
{
WebResponse WebResponse = request.GetResponse();
dataStream = WebResponse.GetResponseStream();
StreamReader StreamReader = new StreamReader(dataStream);
return StreamReader.ReadToEnd();
}
catch (WebException ex)
{
return new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
}
}
I have succeeded getting tickers and my balance from the API, so the problem is not because of the signature or headers.
I have tried changing the request to upper / lower case, and adding the parameters as request headers, with and without them in URL.
Thanks for the help!
Ok so there was no problem at all, LiveCoin exchange doesn't work with BTC-USDT pair, only with BTC-USD. So the response was correct, even tough it was a bit messy.

One Drive API returns invalid Access Token

The authentication process is not working now.(It was working earlier). By following the documentation I'm trying to get the access token from a refresh token. I successfully can get a access token. But it's not valid. I'm setting it as Bearer and send it in my GET request and it returns the following JSON
{"error":{"code":"accessDenied","message":"Access Denied"}}
Here is the code sample
String messageBody = "client_id=" + "9b1a6dbb-7e1f-41b5-b448-9f328169411e" + "&redirect_uri=" + returnURL + "&client_secret={cleindsecret}
+ "&refresh_token={refreshtoken}&grant_type=refresh_token";
RequestBody oAuthCodeRedeemBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
messageBody);
Request request = new Request.Builder().url("https://login.live.com/oauth20_token.srf")
.post(oAuthCodeRedeemBody).build();
String responseBody = null;
OkHttpClient client = new OkHttpClient();
client.setFollowRedirects(false);
Response response;
String accessToken = null;
try {
response = client.newCall(request).execute();
responseBody = response.body().string();
resp = (JSONObject) jsonParser.parse(responseBody);
} catch (IOException | ParseException e) {
e.printStackTrace();
}
accessToken = (String) resp.get("access_token");
I'm getting a Access Token here. But I can't use it to do any work.
Request request2 = new Request.Builder().url("https://api.onedrive.com/v1.0/drive/items/1ED8983F38E94F01!107/children").header("Authorization", "Bearer " + accessToken).get().build();
The response for the above code is returned as
{"error":{"code":"accessDenied","message":"Access Denied"}}
What is the reason here. Is the API returning me a invalid access token or is something wrong in my code?

HttpWebRequest.GetResponse() times out after some time

I have application that sends requests to same REST server constantly and after some time HttpWebRequest.GetResponse() starts timing out i've noticed that whenever i increase System.Net.ServicePointManager.DefaultConnectionLimit it takes it longer to start timing out again, which should mean that those requests are staying active, but as far as i know i'm closing all of them.
Here is method i'm using for my requests.
Current DefaultConnectionLimit is set to 10.
Also there is 1 request that is going on throughout most of applications lifetime.
I'm using .NET Compact framework and REST server is written using WCF (.NET 4.5)
public static string HttpRequest(string request, string method, string contentType, int timeout)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PodesavanjaManager.TrenutnaPodesavanja.PutanjaServisa + "/" + request);
req.Method = method;
req.ContentType = contentType;
req.Timeout = timeout;
req.KeepAlive = false;
if(method == "POST")
req.ContentLength = 0;
using(Stream stream = req.GetResponse().GetResponseStream())
{
using(StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
reader.Close();
}
stream.Close();
stream.Flush();
}
return result;
}
EDIT new version of method:
public static string HttpRequest(string request, string method, string contentType, int timeout)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PodesavanjaManager.TrenutnaPodesavanja.PutanjaServisa + "/" + request);
req.Method = method;
req.ContentType = contentType;
req.Timeout = timeout;
req.KeepAlive = false;
if(method == "POST")
req.ContentLength = 0;
using (HttpWebResponse resp =(HttpWebResponse) req.GetResponse())
{
using (Stream stream = resp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
reader.Close();
}
}
}
GC.Collect();
return result;
}
I agree it does behave like the connection is still in use by a resource that has not been closed. The documentation for HttpWebResponse mentions:
You must call either the Stream.Close or the HttpWebResponse.Close method to close the response and release the connection for reuse. It is not necessary to call both Stream.Close and HttpWebResponse.Close, but doing so does not cause an error.
I was hoping for a more straightforward description like "you must either close the stream returned by GetResponseStream or call the HttpWebResponse.Close method - but if my interpretation of the documentation is correct, your code is fine.
We use HttpWebRequest in our CE applications as well, and always put the response in a using block as well - you could try this:
using(HttpWebResponse response = (HttpWebResponse)req.GetResponse())
using(Stream stream = response.GetResponseStream())
{
// ...
}
Also have you checked your code for other HttpWebRequest usages, just to be sure?

Google API HTTP 401 - Token invalid - AuthSub token has wrong scope

I'm struggling with google api for a few days while sending a post request to Google sites API via C# application.
First I redeem the authorization code from google's servers by a GET request:
https://accounts.google.com/o/oauth2/auth?
scope=email%20profile&
state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.mydomain/myHome&
redirect_uri=http://localhost&
response_type=code&
client_id= // CLIENT ID here...
access_type=online&
approval_prompt=auto
In the redirect uri I got the authorization code which I use to claim the
access token:
string RequestUrl;
RequestUrl = "https://www.googleapis.com/oauth2/v3/token";
WebRequest request = WebRequest.Create(RequestUrl);
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "code=4/aPJAhLvlGLxw1fjKDCOpEQjfoVtNDZYq7FzvrziUero#&" +
"client_id=//cilent id here&" +
"client_secret=client secret here&" +
"redirect_uri=http://localhost&" +
"grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
The response containing the token looks like that:
{
"access_token": "ya29.pAGX8f4e0ZyBazzq5rxWVS6lL1jRyj0_GCog5UEO3FiGT2h4cj10jee4ziAoA09vHRoVejN5p7Iw",
"token_type": "Bearer",
"expires_in": 3600,
"id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjE2NWQ2MzcwZTgzOTI5YmE4Y2E4ZWU5OTMzZTExZjg2Yzg4YzAwNjUifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTA1OTc0NjQwMTUzNzU0NjU1MDE5IiwiYXpwIjoiOTkwMzUxMjA1MzY4LXBudGYxZXNtaXQ3a3Zlbmg5cnRvbW5pMmdhMmY0N2ZsLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJuaXIuazFAaGFpZmFuZXQub3JnLmlsIiwiYXRfaGFzaCI6Imc5MU5wOVRYS2JUaVEzcFpTM2Ewa1EiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXVkIjoiOTkwMzUxMjA1MzY4LXBudGYxZXNtaXQ3a3Zlbmg5cnRvbW5pMmdhMmY0N2ZsLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiaGQiOiJoYWlmYW5ldC5vcmcuaWwiLCJpYXQiOjE0MzU4MjI2ODAsImV4cCI6MTQzNTgyNjI4MH0.CeaQ8S3GG-yeAwqjU1ixdB7ro2SVKp2QdVTXNWl6196oJeQU1LFLpZ9FtrpNEGSDKHXrO5zx0ldE52RYw8TwMKILUqqCHLOewVJQMjZ6tiPzt-b-qeUta6Op4Z9HerwkMK2sofl88G-XZ6jKc7gk1gGPVcATBU7x0-QPRhQxmDUzP7zceVeoOtBD8g7liVHakK9sA5RNonGt-N6SvzECqhSLss7kDuXc4dStnENhyv_9oTIpvVsQplE-cJz7fDHC7mkW7BfwsgKBE8XbruBz5-o3AG5RVGyUTYqDaoq9qr3_NqckiRISUS127scaYwcYPE22Q8L_2AnpfJU0vuxo6g"
}
And the final step is to call the google api using the access_token
this way:
HttpWebRequest req = (HttpWebRequest)System.Net.WebRequest.Create("https://sites.google.com/feeds/site/mydomain");
req.ContentType = "application/atom+xml";
req.Host = "sites.google.com";
req.Method = "POST";
req.Headers["Gdata-version"] = "1.4";
req.Headers["Authorization"] = "Bearer ya29.pAGX8f4e0ZyBazzq5rxWVS6lL1jRyj0_GCog5UEO3FiGT2h4cj10jee4ziAoA09vHRoVejN5p7Iw";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("<entry xmlns='http://www.w3.org/2005/Atom' xmlns:sites='http://schemas.google.com/sites/2008'><title>Source Site</title><summary>A new site to hold memories</summary><sites:theme>slate</sites:theme></entry>");
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
try
{
using (System.Net.WebResponse resp = req.GetResponse())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
string i = sr.ReadToEnd().Trim();
}
}
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
But at the end of this step I get a 401 http error.
Token invalid - AuthSub token has wrong scope
What am I doing wrong?
Thanks in advance
you are authenticating your users using the following scopes
scope=email%20profile&
The Sites Data API uses the following scope: https://sites.google.com/feeds/.

how to send api key to pushbullet api

i try to get the list of devices from pushpullet API
i'm using this code
string api = "my api key";
string url = "https://" + api + ":#api.pushbullet.com/v2/devices";
Uri uri = new Uri(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
string result = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
i get 401 "No valid API key provided."
when i try it on postman
it's work fine and i get the response.pushbullet api