Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect API from PowerShell with OAUTH 2.0?

Tags:

powershell

I am new in powershell, I need to connect to an API that has OAUTH2.0 authentication, the API generates a file in json format.

If I run the script from POWESHELL ISE it works correctly, it authenticates and downloads a json file

$application = "https://api.xxxx.com/token";
$username = "myuser";

$password = "mypassword";

$creds = @{
    username = $username
    password = $password
    grant_type = "password"    
};

$header_token = @{"Content-Type" = "application/x-www-form-urlencoded"}
$header_Out = @{"Accept" = "application/json" ; "authorization" = "bearer $token"}

$datestart = (Get-Date).addDays(-1).tostring(“yyyy-MM-dd”)
$dateend = (Get-Date).addDays(-1).tostring(“yyyy-MM-dd”)

$response = Invoke-RestMethod "$application" -Method Post -Body $creds -Headers $headers;

$token = $response.access_token;

Invoke-WebRequest -Uri "https://api.xxxx.com/api/TrafficData/Hourly?from=$datestart&to=$dateend" -Header $header_Out -OutFile "G:\Traffic.json"
$host.enternestedprompt()

but if i run it from ps1 file it generates authentication error

Error

Anyone know what might be happening?

Thanks for your help

like image 674
KmiloRojas Avatar asked Sep 03 '25 07:09

KmiloRojas


1 Answers

As far as I understand it works on ISE because you develop it inside ISE in the first attempt you give a value to $token that was kept in the session for the second attempt.

Can you just try to add the line in comment ?

$application = "https://api.xxxx.com/token";
$username = "myuser";

$password = "mypassword";

$creds = @{
    username = $username
    password = $password
    grant_type = "password"    
};

$header_token = @{"Content-Type" = "application/x-www-form-urlencoded"}
$header_Out = @{"Accept" = "application/json" ; "authorization" = "bearer $token"}

$datestart = (Get-Date).addDays(-1).tostring(“yyyy-MM-dd”)
$dateend = (Get-Date).addDays(-1).tostring(“yyyy-MM-dd”)

$response = Invoke-RestMethod "$application" -Method Post -Body $creds -Headers $header_token

$token = $response.access_token;
# JPB : Here, you receive the token so you use it
$header_Out = @{"Accept" = "application/json" ; "authorization" = "bearer $token"}

Invoke-WebRequest -Uri "https://api.xxxx.com/api/TrafficData/Hourly?from=$datestart&to=$dateend" -Header $header_Out -OutFile "G:\Traffic.json"
$host.enternestedprompt()
like image 200
JPBlanc Avatar answered Sep 05 '25 00:09

JPBlanc