Interacting with an API using JWT - api

How do I interact with an API using JWT.
I've been given an API url, an integration key and a bearer, and I've been told to get my token with "POST integration key"
I need to get data out of there system and into our MS SQL database, preferably using an SSIS package.
I've used a REST API using curl before to update and get my IP address, I just had to set up an API key through the website and run a command like the below.
curl -u abcdabcd-abcd-abcd-abcd-abcdabcdabcd:x -X GET https://web.site.com/api/v1/addresses.json
I understand what JWT is a little, as in it's encoded as header.payload.signature, but i'm confused as to how do I get the data out of there system into mine using one.
What is the bearer I've been given?
Will I have to use my integration key and bearer to get a JWT from there system?
Will I then use that JWT to interact with there API?
Will it be as simple as the curl command above or will I need to write a script using one of the libraries on jwt.io

Eventually after about 10 emails between the supplier/developer asking for proper documentation and him telling me his system uses JWT, he sent me screenshots of how he tests the API using postman. From his screenshots I was able to figure out what needs to be done, below is my powershell implementation if it benefits anyone.
#$fromdate = (Get-Date).AddDays(-7)
$fromdate = '01/01/2016'
[string]$body = '{"IntegrationKey":"abcdabcd-abcd-abcd-abcd-abcdabcdabcd"}'
$URI = "https://web.site.com/api/token"
# -ProxyUseDefaultCredentials
(New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
[string]$jwt = Invoke-WebRequest $uri -Method post -ContentType 'application/json; charset=UTF-8' -Body $body
$headers = #{"Authorization"="Bearer "+ $jwt.replace("`"","")}
$uri = "https://web.site.com/api/GetData?startDate=" + $fromdate
$response = ".\ResponseData.json"
Invoke-WebRequest $uri -Method get -Headers $headers -TimeoutSec 6000 -OutFile $response

Related

req.headers.authorization is undefined when I make a POST request to my API route in production (works in local dev server)

When I serve my application locally, I can access req.headers.authorization to read my Bearer Token. The same code is used in my deployed application, but when I make the same POST request to my live API route, req.headers is undefined in my NextJS API route. Why is this the case? Am I missing something about req.headers in NextJS that is unique to a deployed application?
Happy to provide more information as necessary! Thank you!
export default async function handler(req, res) {
console.log('req ' + req);
console.log('req.headers ' + req.headers);
console.log('req.headers.authorization: ' + req.headers.authorization);
// ...etc.
When I run the dev server, I can read the Bearer Token successfully, and I can read it in the logs shown above, but in production the requests' req.headers.authorization is undefined.
I've tried accessing the Bearer Token in my request headers, but I can only do so in a development server environment. This fails when I make the very same request to my live, hosted application.
I was able to hit the endpoint and use my Bearer token by making a curl request and adding 'www' to the URL:
curl --request POST \
--url 'https://www.example.com/api/my_route' \
--header 'Authorization: Bearer ${{ secrets.EMAIL_ROUTE_SECRET }}'
I'm not sure what fixed it -- might be an issue with thunder client.

GCP REST api authentication missing

I have created a job of JDBC to BigQuery using the web interface and it worked just fine.
Now I want to create the same job from the REST API of GCP so I took the rest equivalent of the request from the site and tried to send it from Postman.
I'm sending POST request for the following URL:
https://dataflow.googleapis.com/v1b3/projects/test-data-308414/templates:launch?gcsPath=gs://dataflow-templates/latest/Jdbc_to_BigQuery
which I got from the example in the GCP documentation.
I also pass the JSON that the GCP gave me in the body.
And the API key as get parameter in the next format "?key=[API_KEY]"
I'm getting 401 response from the server with the following message:
Request is missing required authentication credential. Expected OAuth
2 access token, login cookie or other valid authentication credential.
See
https://developers.google.com/identity/sign-in/web/devconsole-project.
With a status of:
UNAUTHENTICATED
I looked up at the link and found a tutorial on how to create google authentication on the front end
witch is not helpful to me.
I'm pretty sure that I'm passing the API key in the wrong format and that the reason it failed to authenticate.
But I couldn't find any documentation that says how to do it correctly.
PS> I have also tried passing it at the headers as I saw in one place
in the next format
Authorization : [API_KEY]
but it failed with the same message
Few days back I was trying to integrate GCP into MechCloud and struggling to figure out how to invoke a microservice ( which is acting as a proxy to GCP) with credentials for different projects which will be passed to this microservice on the fly. I was surprised that in spite of spending good amount of time I could not figure out how to achieve it because GCP documentation is focused on working with one project credentials at a time using application default credentials. Another frustrating thing is that API explorer shows both OAuth 2.0 and API Key by default for all the APIs when the fact is that API Key is hardly supported for any API. Finally I found the solution for this problem here.
Here are the steps to invoke a GCP rest api -
Create a service account for your project and download the json file associated with it.
Note down values of client_email, private_key_id and private_key attribues from service account json file.
Define following environment variables using above values -
GCP_SERVICE_ACCOUNT_CLIENT_EMAIL=<client_email>
GCP_SERVICE_ACCOUNT_PRIVATE_KEY_ID=<private_key_id>
GCP_SERVICE_ACCOUNT_PRIVATE_KEY=<private_key>
Execute following python code to generate jwt_token -
import time, jwt, os
iat = time.time()
exp = iat + 3600
client_email = os.getenv('GCP_SERVICE_ACCOUNT_CLIENT_EMAIL')
private_key_id = os.getenv('GCP_SERVICE_ACCOUNT_PRIVATE_KEY_ID')
private_key = os.getenv('GCP_SERVICE_ACCOUNT_PRIVATE_KEY')
payload = {
'iss': client_email,
'sub': client_email,
'aud': 'https://compute.googleapis.com/',
'iat': iat,
'exp': exp
}
private_key1 = private_key.replace('\\n', '\n')
# print(private_key1)
additional_headers = {'kid': private_key_id}
signed_jwt = jwt.encode(
payload,
private_key1,
headers=additional_headers,
algorithm='RS256'
)
print(signed_jwt)
Use generated jwt token from previous step and use it as a bearer token to invoke any GCP rest api. E.g.
curl -X GET --header 'Authorization: Bearer <jwt_token>' 'https://compute.googleapis.com/compute/v1/projects/{project}/global/networks'
The best practice to authenticate a request is to use your application credentials. Just make sure you installed the google cloud SDK.
curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d #request.json \
https://dataflow.googleapis.com/v1b3/projects/PROJECT_ID/templates:launch?gcsPath=gs://dataflow-templates/latest/Jdbc_to_BigQuery

how to construct header for (REST API) azure storage SAS (shared accesss signature)

I am debugging a client application calling REST API embedded with AZURE storage SAS-shared access signature to access azure storage resource. However, it is not getting through. The azure threw out an error stating that the mandatory header is missing, and abort the operation.
The REST API is fairly simple, although it is embedded with the SAS token generated by the azure storage account. The client application uses the REST API to write data into an azure blob.
is there anywhere I can find a good example showing how to generate the header for the REST API (SAS)? I need to find out the exact layout of the header (such as the type of information that needs to be embedded in the header.
Also, do I need to register my client application with the Azure AD?
I didn't think my client application needs to be registered with the AZURE since that is why we have client-side SAS. But, I could be wrong. Therefore, any input will be appreciated.
Thanks in advance.
If you use sas token to call Azure blob rest api, the request URL should be like
https://myaccount.blob.core.windows.net/<cantianer>/<blob>?<sastoken>
For example
$accountName=""
$accountKey=""
$containerName="output"
$blobName="test.txt"
$context= New-AzStorageContext -StorageAccountName $accountName -StorageAccountKey $accountKey
$sas = New-AzStorageAccountSASToken -Service Blob -ResourceType Service,Container,Object -Permission "rwdlacx" -Context $context
$body = "Hello"
$headers=#{"x-ms-blob-type"="BlockBlob"; "Content-Type"="text/plain"}
$url="https://$accountName.blob.core.windows.net/$containerName/$blobName$sas"
Invoke-WebRequest -Uri $url -Method Put -Headers $headers -Body $body -UseBasicParsing

Microsoft speech recognition api

I want to ask a bit about Authentication of this API
Do "The token" of the response have some expired time or something? or is it for eternity?
Documentation link is here :
https://www.microsoft.com/cognitive-services/en-us/Speech-api/documentation/API-Reference-REST/BingVoiceRecognition#Authorize
Expiry is 10 minutes. Its specified in the documentation : https://www.microsoft.com/cognitive-services/en-us/speech-api/documentation/API-Reference-REST/BingVoiceRecognition
Bing Speech Team
The token is a JSON Web Token (JWT), which—unless it's encrypted—can be decoded to inspect its contents (a web service to perform that task can be found here).
Expiry claims are set with the exp property in the resulting JSON document.
If you want to not have to login each time instead of using the 'Authorization': 'Bearer {TOKEN}' header you could use the 'Ocp-Apim-Subscription-Key': '{YOUR AZURE TOKEN}' in order to not have to make a authorisation factory or more requests than necessary to the application and make it faster
NOTE: {TOKEN} is a JWT token like
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzY29wZSI6Imh0dHBzOi8vc3BlZWNoLnBsYXRmb3JtLmJpbmcuY29tIiwic3Vic2NyaXB0aW9uLWlkIjoiZmFhZTNlYTkxNmI1NGMxZWEyODY4MDlhYTg3ZWE1MmUiLCJwcm9kdWN0LWlkIjoiQmluZy5TcGVlY2guUHJldmlldyIsImNvZ25pdGl2ZS1zZXJ2aWNlcy1lbmRwb2ludCI6Imh0dHBzOi8vYXBpLmNvZ25pdGl2ZS5taWNyb3NvZnQuY29tL2ludGVybmFsL3YxLjAvIiwiYXp1cmUtcmVzb3VyY2UtaWQiOiIiLCJpc3MiOiJ1cm46bXMuY29nbml0aXZlc2VydmljZXMiLCJhdWQiOiJ1cm46bXMuc3BlZWNoIiwiZXhwIjoxNTAwODgxNjIzfQ.KdlCrIJ_H0jxs1yyeyYxYR7ucbLuFKT__ep7lGJmGbU
NOTE2: {YOUR AZURE TOKEN} is like d5kals90935b40809dc6k38533c21e85 and you find it here
The request would look like this:
curl -v -X POST "https://speech.platform.bing.com/speech/recognition/interactive/cognitiveservices/v1?language=es-ES&locale=es-ES&format=simple&requestid=req_id" -H "Ocp-Apim-Subscription-Key: d5kals90935b40809dc6k38533c21e85" -H 'Transfer-Encoding: chunked' -H 'Content-type: audio/wav; codec="audio/pcm"; samplerate=8000' --data-binary #"{BINAYFILE}.wav"

RestSharp Oauth2 authentication Cherwell restful api

I normally don't ask questions here because most of the times I can find answers. But at this moment I haven´t find one, and I am really stuck. I have a problem trying to get access token for the Cherwell api: http://13.88.176.216/CherwellAPI/Swagger/ui/index#!/Service/Service_Token I used postman to generate this code:
This is relevant to Cherwell Service Management's V8+ REST API.
Code that throws server run time exception:
string user = "myUser";
string password = "myPassword";
var client1 = new RestClient("http://13.88.176.216/cherwellapi/token?auth_mode=Internal");
client.Authenticator = new HttpBasicAuthenticator(user, password);
var request1 = new RestRequest(Method.POST);
request1.AddHeader("content-type", "application/x-www-form-urlencoded");
request1.AddHeader("cache-control", "no-cache");
request1.AddParameter("application/x-www-form-urlencoded", "grant_type=password&client_id=my_client_id&client_secret=my_client_secret", ParameterType.RequestBody);
IRestResponse response = client1.Execute(request1);
The thing is when I execute the same method from the swagger ui (http://13.88.176.216/CherwellAPI/Swagger/ui/index#!/Service/Service_Token) I can get the token without getting any error.
Details of the request in CURL:
Curl
curl -X POST
--header "Content-Type: application/x-www-form-urlencoded"
--header "Accept: application/json" -d "grant_type=password&client_id=my_client_id&client_secret=my_client_secret&username=my_user_name&password=my_password" "http://13.88.176.216/CherwellAPI/token?auth_mode=Internal"
Request URL
http://13.88.176.216/CherwellAPI/token?auth_mode=Internal
This is the response body from the swagger ui test, not my code:
{
"access_token": "the_acces_token",
"token_type": "bearer",
"expires_in": 1199,
"refresh_token": "the_refresh_token",
"as:client_id": "client_key",
"username": "user",
".issued": "date",
".expires": "other_date"
}
Any help will be appreciated.
Try including the username/password as part of your form encoded data.
Drop the authenticator section, it shouldn't be necessary for this part.
So,
request1.AddParameter("application/x-www-form-urlencoded", "grant_type=password&client_id=my_client_id&client_secret=my_client_secret&username=(yourusernamehere)&password=(yourpasswordhere)", ParameterType.RequestBody);
I actually just recorded a video on this not too long ago (using a browser rest client, not C#, but you get the picture), that should post to our youtube channel soon at https://youtube.com/beyond20llc - I can send this video to you if you'd like to see it before it reaches youtube.
The data I sent when I was authenticating for a token essentially looked like the following:
grant_type=password&
client_id=1234567890&
username=CSDAdmin&
password=CSDAdmin
(Of course, CSDAdmin being the default username/password on a fresh installation of Cherwell - if you're CSDAdmin account still has these credentials, change immediately as this is a well-known default pass).
Have you tried using the swagger code generation tool as documented in the Cherwell documentation?
Once you have generated the client code, you will have wrapper data structures for all Cherwell REST API requests and responses.
Using Swagger Code Gen
You will need to install Maven and the Java Development kit.