Invalid nonce and timestamp Garmin access token API response using oauthSwift - swift

I am trying to connect Garmin with my app. I have authToken and verifier but when I call https://connectapi.garmin.com/oauth-service/oauth/access_token API I get "invalid nonce and timestamp response.
This is code below to make my signature header
var parameter = OAuthSwift.Parameters()
parameter = ["oauth_verifier": "HGJNBBHJ", "oauth_token": "d9209df0-044e-4872-817e-51caa0b38edb"]
let oauthswift = OAuth1Swift(
consumerKey: "********",
consumerSecret: "********"
)
this is the code to make header
let head = oauthswift.client.credential.makeHeaders(URL(string: "https://connectapi.garmin.com/oauth-service/oauth/access_token")!, method: .POST, parameters: parameter)
this is the header I got.
["Authorization": "OAuth oauth_consumer_key=\"********\", oauth_nonce=\"01C7E0DF\", oauth_signature=\"uAZhDpkU3REnm%2Fs%2BEbEK9KPT3wM%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1585117527\", oauth_token=\"d9209df0-044e-4872-817e-51caa0b38edb\", oauth_verifier=\"NvyJlPDlzY\", oauth_version=\"1.0\""]
but when I call https://connectapi.garmin.com/oauth-service/oauth/access_token I get invalid nonce and timestamp error in response.
anyone who can help me out?

#Awais Shahid you need to update oauth_nonce & oauth_timestamp for each api call.
So if it is used once and when you try to use same oauth_nonce & oauth_timestamp second time even for same api it will throw this error.

Related

Calling API from Saleforce is giving error code 500

I have a REST API to callout from Salesforce.
The authorization of the API is through access token.
I am able to get the access token through POST request in Salesforce. Also tested from Postman through that token and able to get a successful response.
I am using the below code to callout the API using the access token:
String endpoint_x = '*****';//Putting my endpoint here
Http httpObject;
HttpResponse response;
String accessToken;
accessToken = MyUtilityClass.getAccessToken();
jsonBody = json.serializePretty('', true);//Yes, My JSON is empty
HttpRequest request = new HttpRequest();
request.setEndpoint(endpoint_x);
request.setHeader('Authorization', 'Bearer '+accessToken);
request.setMethod('POST');
request.setBody(jsonBody);
httpObject = new Http();
response = httpObject.send(request);
System.debug('Response=' + response);
Getting Response value as below:
System.HttpResponse[Status=Internal Server Error, StatusCode=500]
I have tried putting '{}' in the Jsonbody. Added 'Content-Type' in header but nothing worked.
Where should I lookout for this?
In the Postman, I was not putting anything in the body, and getting a successful response.
To get the same behaviour, I was using empty string in Apex, like this:
jsonBody = json.serializePretty('', true);
But the parser was not working correctly.
To solve this, I created a class without any field:
class ClassForEmptyBody{
}
And used object of that class in the serializer:
ClassForEmptyBody classForEmptyBodyObject = new ClassForEmptyBody();
jsonBody = json.serializePretty(classForEmptyBodyObject , true);
Why are you passing json body if nothing is in there. Just skip setbody code and try.

Axios Encrypted POST parameters

I want to use the API from bitgrail (docs: https://bitgrail.com/api-documentation). And request the amount of balances. To do that you have to set a SIGNATURE which includes the encrypted post parameters using HMAC-SHA512 with ur API-Secret.
So you have to sent this data:
Header:
KEY - Public API key
SIGNATURE - encrypted POST parameters with HMAC-SHA512 alghoritm using your secret API key
Data:
nonce - Integer number, always greater then nonce of previous call.
But everytime I try to send the request I get an 'Authentication failed'-Error from Bitgrail.
The params are set like so:
params = {}
params.nonce = n();
and then encrypted like this:
let hmac = crypto.createHmac('sha512', 'MYSECRET');
let digest = hmac.update(params.toString()).digest('hex');
let signature = new Buffer(digest).toString('base64');
Maybe the 'params.toString()' is not working. Do I have to set the params variable as an array?
I figured it our by myself by using const { URLSearchParams } = require('url');
and deleting this line: let signature = new Buffer(digest).toString('base64'); and just using the digest as signature.

How to add a http header when post request to a servicestack web api using servicestack swift plugin?

First below is a very straightforward code that post a req to the api.
let req = PurchaseRequest()
req.cellphone = "5101111111"
req.amount = 6
let client = JsonServiceClient(baseUrl: "http://example.com/webapi")
let response = try! client.post(req)
Now, how do I add a Http header to the request? For example, there is a http header called "Authorization" and we usually use this header to provide token, to authenticate users. How do I do that?
let client = JsonServiceClient(baseUrl: "http://example.com/webapi")
client.requestFilter = { (req:NSMutableURLRequest) in
req.addValue("FJEUJFJSKEJF#$"/*a token value*/, forHTTPHeaderField: "Authorization")
}
So I found the property called requestFilter of the jsonserviceclient, which I can then get the standard nsmutableurlrequest so the rest is easy, just plain old swift code, where I just add my token value to the Authorization http header. My code is doing exactly that.

Getting Facebook Auth Token Using FSharp

I am trying to get the OAuth token from facebook using the following code:
let applicationId = "12345"
let applicationSecret = "12345"
let tokenBuilder = new StringBuilder()
tokenBuilder.Append("https://graph.facebook.com/v2.3/oauth/access_token?")
tokenBuilder.Append("client_id=")
tokenBuilder.Append(applicationId)
tokenBuilder.Append("&redirect_uri=")
tokenBuilder.Append("https://www.facebook.com/connect/login_success.html")
tokenBuilder.Append("&client_secret=")
tokenBuilder.Append(applicationSecret)
let tokenUri = tokenBuilder.ToString()
let tokenClient = new WebClient()
let tokenResponse = tokenClient.UploadString(tokenUri,String.Empty)
When I run it, I get this:
System.Net.WebException: The remote server returned an error: (400)
Bad Request.
Can anyone tell me what I am doing wrong? There are a bunch of configurations that I can make for the application that I guessed like this:
Not exactly the answer to your question, but this is how you can get the OAuth2 bearer token using FacebookClient from Facebook SDK:
// nuget Facebook package
open Facebook
type Credentials() = // There are better ways around to make a POCO, anyways...
member __.client_id with get() = "...your facebook app id here"
member __.client_secret with get() = "...your facebook app secret here"
member __.grant_type with get() = "client_credentials"
let fb = FacebookClient()
let token = fb.Get("oauth/access_token", Credentials())
getting back into token something like:
seq [[access_token, 239907752864330+s3c5obp-fO7DoVX4pPiN69OdAS4]]

Azure encoding job via REST Fails

I am trying to upload a video and encode it via azure rest service.
I have now hit the step of encoding the video but I am having difficulties with the request.
The following code shows my request:
var joburl = res.RequestMessage.RequestUri + "Jobs";
client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + token);
client.DefaultRequestHeaders.Add("x-ms-version", "2.8");
client.DefaultRequestHeaders.Add("DataServiceVersion", "3.0");
client.DefaultRequestHeaders.Add("MaxDataServiceVersion", "3.0");
client.DefaultRequestHeaders.Add("x-ms-date", date);
//accept
t = new NameValueHeaderValue("odata", "verbose");
type = new MediaTypeWithQualityHeaderValue("application/json");
type.Parameters.Add(t);
client.DefaultRequestHeaders.Accept.Add(type);
result = await client.PostAsync(joburl,json);
the url:https://wamsamsclus001rest-hs.cloudapp.net/api/Jobs
the json:
{"Name":"khgfiuydencodingjob","InputMediaAssets":[{"__metadata":{"Uri":"https://wamsamsclus001rest-hs.cloudapp.net/api/Assets('nb%3acid%3aUUID%3ad037b321-cd1c-43a9-9607-c4910fa7a85b')"}}],"Tasks":[{"Configuration":"H264 Adaptive Bitrate MP4 Set 720p","MediaProcessorId":"nb:mpid:UUID:1b1da727-93ae-4e46-a8a1-268828765609","TaskBody":"<?xml version=\"1.0\"encoding=\"utf-8\"?><taskBody><inputAsset>JobInputAsset(0)</inputAsset><outputAsset>JobOutputAsset(0)</outputAsset></taskBody>"}]}
The bearer token works as I use it for other request.
But I get a bad request 400 with the followin error message:
{"error":{"code":"","message":{"lang":"en-US","value":"Parsing request content failed due to: Make sure to only use property names that are defined by the type"}}}
Can anyone spot the error.
Thank you for the help
Okay I got it to work. Needed a odata=verbose in my json/string content - like this:
var jobInJson = JsonConvert.SerializeObject(job);
json = new StringContent(jobInJson, Encoding.UTF8);//,
json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
I tried this earlier however I got a error 500 but now it is working.