I want to send access token request for bearer token to here api.(https://developer.here.com/tutorials/how-to-authenticate-with-here-oauth/) They showed example using node. But I tried the same way in c#. But I got 400 bad request. My code is as following:
var url = "https://account.api.here.com/oauth2/token";
String id = "key id";
String secret = "key secret";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
var timeStamp = ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString();
var nonce = Convert.ToBase64String(Encoding.UTF8.GetBytes(timeStamp));
var signatureBaseString = Escape(httpWebRequest.Method.ToUpper()) + "&";
signatureBaseString += url.ToLower() + "&";
signatureBaseString +=
"oauth_consumer_key=" + id + "&" +
"oauth_nonce=" + nonce + "&" +
"oauth_signature_method=" + "HMAC-SHA1" + "&" +
"oauth_timestamp=" + timeStamp + "&" +
"oauth_version=" + "1.0";
var key = secret;
var signatureEncoding = new ASCIIEncoding();
var keyBytes = signatureEncoding.GetBytes(key);
var signatureBaseBytes = signatureEncoding.GetBytes(signatureBaseString);
string signatureString;
using (var hmacsha1 = new HMACSHA1(keyBytes))
{
var hashBytes = hmacsha1.ComputeHash(signatureBaseBytes);
signatureString = Convert.ToBase64String(hashBytes);
}
string SimpleQuote(string s) => '"' + s + '"';
var header =
"Content-Type=application/x-www-form-urlencoded" + "," +
"Authorization=OAuth" + "," +
"oauth_consumer_key=" + SimpleQuote(id) + "," +
"oauth_nonce=" + SimpleQuote(nonce) + "," +
"oauth_signature_method=" + SimpleQuote("HMAC-SHA1") + "," +
"oauth_timestamp=" + SimpleQuote(timeStamp) + "," +
"oauth_version=" + SimpleQuote("1.0") + "," +
"oauth_signature= " + SimpleQuote(signatureString);
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, header);
string postData = "grant_type=client_credentials";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
httpWebRequest.ContentLength = byte1.Length;
var newStream = httpWebRequest.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(byte1, 0, byte1.Length);
newStream.Close();
var response = httpWebRequest.GetResponse();
May be I am generating the signature in wrong way. But I only have key id and secret and I managed to implement this far. Please help me pointing the mistake I made.
Would you please have a look below article? Getting (401) UnAuthorized error on some requests not all, but most Try to use different lib such as HttpClient or RestClient.