Search code examples
c#oauth-2.0nest-api

Unauthorized error when trying to get Nest Access Token


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;
}

Solution

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