Unauthorized error when trying to get Nest Access Token - c#

Everything was working fine until a couple days ago, I started getting an Unauthorized error when trying to get a Nest Access Token. I've double checked and the client ID and client secret code are all correct. Any ideas on what could be causing it?
HttpWebRequest request = WebRequest.CreateHttp("https://api.home.nest.com/oauth2/access_token?");
var token = await request.GetValueFromRequest<NestToken>(string.Format(
"client_id={0}&code={1}&client_secret={2}&grant_type=authorization_code",
CLIENTID,
code.Value,
CLIENTSECRET));
public async static Task<T> GetValueFromRequest<T>(this HttpWebRequest request, string postData = null)
{
T returnValue = default(T);
if (!string.IsNullOrEmpty(postData))
{
byte[] requestBytes = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var postStream = await request.GetRequestStreamAsync())
{
await postStream.WriteAsync(requestBytes, 0, requestBytes.Length);
}
}
else
{
request.Method = "GET";
}
var response = await request.GetResponseAsync();
if (response != null)
{
using (var receiveStream = response.GetResponseStream())
{
using (var reader = new StreamReader(receiveStream))
{
var json = await reader.ReadToEndAsync();
var serializer = new DataContractJsonSerializer(typeof(T));
using (var tempStream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return (T)serializer.ReadObject(tempStream);
}
}
}
}
return returnValue;
}

While I can't provide an answer I can confirm the same thing is happening to my iOS app in the same timeframe.
Taking my url and post values works fine using postman in chrome. Alamofire is throwing up error 401, as is native swift test code like yours.
Have Nest perhaps changed their https negotiation?

This turned out to be because of a fault on Nest's end which was later fixed.

Related

Yahoo api for fantasy sports. Cannot figure how to use access token

I have the access token. How can I make a request using the token in c#?
Here is what I have tried unsuccessfully resulting in error 400 Bad Request.
Note: the url was copied from the YQL console
public static void Request(string token)
{
var request =
WebRequest.Create(
#"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20fantasysports.leagues%20where%20league_key%3D'371.l.4019'&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
request.Headers["Authorization"] = $"Bearer {token}";
request.Method = "GET";
request.ContentType = "application/xml;charset=UTF-8";
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
if (stream == null) return;
var reader = new StreamReader(stream, Encoding.UTF8);
var responseString = reader.ReadToEnd();
}
}
}

http get works in browser and postman but get a 401 using c# httpwebrequest

I have a web app hosted in azure. When I use postman to make the request I get a
json result, which is the correcet response. When I try to make the same request via C# using the same token I receive a errpr - The remote server returned an error: (401) Unauthorized.
here is the code I use to make the request.
public string RequestData(string queryString, string token)
{
var request = (HttpWebRequest)WebRequest.Create(queryString);
request.Proxy = GetProxy();
request.Credentials = CredentialCache.DefaultCredentials;
request.PreAuthenticate = true;
request.UseDefaultCredentials = true;
request.Method = "GET";
request.ContentType = "application/json";
request.ContentLength = 0;
request.CookieContainer = new CookieContainer();
request.Headers.Add("authorization", "Bearer " + token);
using (var webresponse = request.GetResponse())
{
if (webresponse.GetResponseStream() == Stream.Null)
{
throw new Exception("Response stream is empty");
}
var response = (HttpWebResponse)webresponse;
if (response.StatusCode != HttpStatusCode.OK)
{
return response.StatusCode.ToString();
}
else
{
return response.StatusCode.ToString();
}
}
}
I have double checked the token to ensure it is correct and it is.
Another point I wanted to mention is that it did not work initially in
Postman without enabling Interceptor. This goes for Advanced Rest Client.
The request did not work until I enabled "XHR" and installed ARC cookie exchange.
I have checked the request headers in Fiddler and noticed there are no additional headers except for the authorization one (which I add as well).
UPDATE:
I got a successfull response in Postman (https://www.getpostman.com/)
and ran the code it generated for c# using RestSharp. In the response
the error thrown was
"You do not have permission to view this directory or page."
Which points to the token not being correct. Which is confusing since it works
in Postman and Advanced Rest Client. Also I must mention I retrieve the token
on each call using the clientid and secret using the following code:
public async static Task<AzureAccessToken> CreateOAuthAuthorizationToken(string clientId, string clientSecret, string resourceId, string tenantId)
{
AzureAccessToken token = null;
var oauthUrl=string.Format("https://login.microsoftonline.com/{0}/oauth2/token", tenantId);
var reqBody = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}",clientId, clientSecret);
var client = new HttpClient();
HttpContent content = new StringContent(reqBody);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
using (HttpResponseMessage response = await client.PostAsync(oauthUrl, content))
{
if (response.IsSuccessStatusCode)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AzureAccessToken));
Stream json = await response.Content.ReadAsStreamAsync();
token = (AzureAccessToken)serializer.ReadObject(json);
return token;
}
return null;
}
}
after checking the log in azure, I saw the following error message:
JWT validation failed: IDX10214: Audience validation failed. Audiences: '00000002-0000-0000-c000-000000000000'. Did not match: validationParameters.ValidAudience: 'f50a9d02-b8f4-408f-aaf8-0046e6cbf7a6' or validationParameters.ValidAudiences: 'null'.
I resolved the issue by adding '00000002-0000-0000-c000-000000000000' to the "Allowed Token Audiences" under Azure Active Directory Settings.
I have called third party API. When I use postman to make the request I get a json result, which is the correct response. When I try to make the same request via C# using the same token I receive a error - The remote server returned an error: (401) Unauthorized. Finally I got the solution.
When I make the login request some cookies will send by the server and that cookie will store in postman. If you see code snippet you will see information about request that is raised by postman.
When I call the Login method I stored the cookies like below:
public ResponseData OnGetResponseFromAPI(string URL, string Method, string PostData = null, Dictionary<string, string> Headers = null, string body = null, string ContentType = "application/json")
{
ResponseData response = new ResponseData();
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var webRequest = (HttpWebRequest)WebRequest.Create(URL);
CookieContainer cookieJar = new CookieContainer();
webRequest.CookieContainer = cookieJar;
webRequest.Method = Method;
webRequest.ContentType = ContentType;
if (Method == "GET")
{
var type = webRequest.GetType();
var currentMethod = type.GetProperty("CurrentMethod", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(webRequest);
var methodType = currentMethod.GetType();
methodType.GetField("ContentBodyNotAllowed", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(currentMethod, false);
}
if (Headers == null)
Headers = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> header in Headers)
{
webRequest.Headers.Add(header.Key, header.Value);
}
if (!string.IsNullOrEmpty(PostData))
{
var RequestStream = new StreamWriter(webRequest.GetRequestStream());
RequestStream.Write(PostData);
RequestStream.Close();
}
if (!string.IsNullOrEmpty(body))
{
byte[] byteArray = Encoding.UTF8.GetBytes(body);
webRequest.ContentLength = byteArray.Length;
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
var ResponseStream = new StreamReader(webRequest.GetResponse().GetResponseStream());
string cookie = string.Empty;
CookieCollection allCookies = cookieJar.GetCookies(webRequest.RequestUri);
foreach (Cookie c in allCookies)
{
cookie = cookie + c.Name + "=" + c.Value+";";
}
cookie = cookie.Substring(0, cookie.LastIndexOf(';'));
var ResponseData = ResponseStream.ReadToEnd();
response.response=ResponseData.ToString();
response.cookie=cookie;
return response;
}
catch (WebException webException)
{
if (webException == null || webException.Response == null)
return null;
var responseStream = webException.Response.GetResponseStream() as MemoryStream;
if (responseStream == null)
return null;
var responseBytes = responseStream.ToArray();
var responseString = Encoding.UTF8.GetString(responseBytes);
response.response = responseString;
return response;
}
}
Whenever I am calling any api method I am sending token and cookie in header like below:
public string DownLoadDocument( string FilePath, string FileName, string token,string cookie)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpWebRequest webRequest;
webRequest = (HttpWebRequest)WebRequest.Create(URL);
webRequest.Method = "GET";
webRequest.ContentType = "application/octet-stream;charset=UTF-8";
webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1";
webRequest.Headers.Add("Cookie", cookie);
webRequest.Headers.Add("Authentication", "Bearer "+token);
webRequest.Headers.Add("Content-Disposition", "attachment");
Stream responseReader = webRequest.GetResponse().GetResponseStream();
using (var fs = new FileStream(FilePath, FileMode.Create))
{
responseReader.CopyTo(fs);
}
}
catch (Exception ex)
{
throw;
}
return FilePath;
}

Payu OrderCreateRequest returns 403

I am integrating payu to my web app. The problem is I can not request new order It returns 403 forbidden in my app but with same data I can get 200 from api doing it postman.
I got token,created authorization,sent headers(authorization,content-type,content-length).
Here is my post method.
var request = (HttpWebRequest)WebRequest.Create(new Uri(Url));
var postData = RawData;//json data
request.Method = "POST";
request.ContentType = ContentType;
if (Headers != null) // add headers
{
foreach (var header in Headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
var data = Encoding.UTF8.GetBytes(postData);
request.ContentLength = data.Length;
using (var stream = new StreamWriter(request.GetRequestStream()))
{
stream.Write(data);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
catch (WebException e)
{
return null;
}
Please add this line.
request.UseDefaultCredentials = true;
or you can see the complete explanation of this error here on stackoverflow.
The remote server returned an error: (403) Forbidden

How to get http content using an given api key like this in C#?

http://ssw.com/profile/?apikey = skdwkdkfkkdj
I tried to use
public async Task<string> GetFromUriAsync(string requestUri, string token)
{
var client = new HttpClient();
client.BaseAddress = new Uri(BaseUri);
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("apikey", "=" + token);
HttpResponseMessage response = await client.GetAsync(requestUri);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
Then it returns null
Am I missing something or is it just totally wrong?
Thanks
You're trying to pass the API key in the header information of your HTTP request. What you need to do is just pass that whole URL without any additional header information.
IE: use "http://ssw.com/profile?apikey=abcdef" as the requestUri and send token as null. Also, remove the setting of the client.DefaultRequestHeaders.Authorization property. Authorization was meant to be a user/pass system and not a token-based system.
To test this, download Fiddler 4 (https://www.telerik.com/download/fiddler). Once you have fiddler installed, on the "Composer" tab, you can test different queries you need by putting the URL directly into the URL box and clicking "Execute". You'll then be able to use the inspectors to see the responses and figure out where you need to go from there.
Here are the classes I use for HTTP GET and POST operations:
public static string HTTPGET(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.Timeout = 100000;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
using (StreamReader resStream = new StreamReader(responseStream))
return resStream.ReadToEnd();
return null;
}
catch (Exception e)
{
Console.WriteLine(url);
Console.WriteLine(e);
return null;
}
}
public static string HTTPPOST(string url, string postData)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "x-www-form-urlencoded";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
using (Stream requestStream = webRequest.GetRequestStream())
requestStream.Write(byteArray, 0, byteArray.Length);
using (Stream responseStream = webRequest.GetResponse().GetResponseStream())
if (responseStream != null)
using (StreamReader responseReader = new StreamReader(responseStream))
return responseReader.ReadToEnd();
return null;
}
catch (Exception e)
{
Console.WriteLine(url);
Console.WriteLine(postData);
Console.WriteLine(e);
return null;
}
}

Consuming REST service with C# code

I am using the following code to get the json result from the service. It works fine for get methods. But when the method type is POST the request address changes to the previous address.
ie;
on the first call to this method the request.address=XXXXX.com:1234/xxx/oldv1.json (method type is get)
and it returns a json string from which I extract another address:XXXXX.com:1234/xxx/newv1.json
and now I call the makerequest method with this endpoint and method type POST, contenttype="application/x-www-form-urlencoded".
When I put breakpint at using (var response = (HttpWebResponse)request.GetResponse()) and checked the request.address value, it was XXXXX.com:1234/xxx/newv1.json
But after that line is executed, the address changes to XXXXX.com:1234/xxx/oldv1.json and the function returns the same response I got with the first Endpoint(XXXXX.com:1234/xxx/oldv1.json).
Can anybody tell what I am doing wrong here?
Is there any better method to consume the service with POST method?
public string MakeRequest(string EndPoint,string Method, string contentType)
{
var request = (HttpWebRequest)WebRequest.Create(EndPoint);
request.Method = Method;
request.ContentLength = 0;
request.ContentType =contentType;
if ( Method == HttpVerb.POST)
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes("username=123&password=123");
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
using (var response = (HttpWebResponse)request.GetResponse())// request.address changes at this line on "POST" method types
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
return responseValue;
}
EDIT: Yesterday I asked THIS Question about consuming the service at client side and many suggested it needs to be done at server side as the other domain might not allow accessing the json result at client side.
The issue was about cookies. As I forgot to set the cookies, the request was getting redirected. I had to set cookie container by using
request.CookieContainer = new CookieContainer();

Categories

Resources