function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dmitry LosyankovDmitry Losyankov 

REST API Username-Password OAuth Authentication on Powershell

Hi guys. I'm new at powershell and scripting, need some help.

I try to authenticate in developers edition by Username-Password OAuth and get list of recources (for example)

I can get access_token succesfully, but next step returned error 400 (bad request)
This is my code:

$url = "https://login.salesforce.com/services/oauth2/token"

$postParams = @{
                grant_type = "password"
                client_id = "[Consumer Key]"
                client_secret = "[1578651120116368499]"
                username = "[useremail]"
                password = "[password+securitytoken]"
               }

$result = Invoke-RestMethod -Uri $url -Method POST -Body $postParams
$access_token = $result.access_token 

$url2 = "https://eu6.salesforce.com/services/data/v37.0/limits/"

$var = Invoke-RestMethod -Uri $url2 -Headers @{"Authorization" = "Bearer " + $access_token}

Please, could you help with this task?
Dmitry LosyankovDmitry Losyankov
I improoved script like this:

cls
$browser = New-Object System.Net.WebClient
$browser.Proxy.Credentials =[System.Net.CredentialCache]::DefaultNetworkCredentials
$url = "https://login.salesforce.com/services/oauth2/token"
$url2 = "https://eu6.salesforce.com/services/data/v37.0/limits/"

$postParams = @{
                grant_type = "password"
                 client_id = "[Consumer Key]"
                client_secret = "[Consumer Secret]"
                username = "[useremail]"
                password = "[password+securitytoken]"
               }

$preAuth = Invoke-RestMethod -Uri $url -Method POST -Body $postParams
#$preAuth

$preAuthToken = @{access_token = $preAuth.access_token}
$preAuthToken

$authValue = "Bearer $preAuthToken"
#$authValue

$headers = @{ Authorization = $authValue }
#$headers

Invoke-WebRequest -Uri $url2 -Method GET -Headers $headers 

At this time error 401 (Unauthorized)

Any ideas?
Arun AArun A
Just change the $authValue = "Bearer $preAuthToken" to below:
$authValue = "Bearer  $($preAuth.access_token)"

This should work.
Avinash ShivaniAvinash Shivani
Your code to get the token was very useful...I was stuck for more than a week before I found your post.  Thanks a lot!
Patrick Van RinsveltPatrick Van Rinsvelt
Nice post here folks! The solution works a dream!