Microsoft Azure get access token API not working with cURL/Ruby but works with powershell

1.8k views Asked by At

I am simply trying to get an access token from client id, client secret and tenant ID. Following powershell command works successfully

Invoke-RestMethod -Uri https://login.microsoftonline.com/TENANT/oauth2/token?api-version=1.0 -Method Post -Body @{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "CLIENTID"; "client_secret" = "SECRET" }

But this curl doesn't work

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "grant_type=client_credentials&resource=https://management.core.windows.net/&client_id=CLIENTID&client_secret=SECRET" "https://login.microsoftonline.com/TENANT/oauth2/token?api-version=1.0"

Neither this ruby script

require 'json'
require 'typhoeus'

url = 'https://login.microsoftonline.com/TENANT/oauth2/token?api-version=1.0'
params = "grant_type=client_credentials&resource=https://management.core.windows.net/&client_id=CLIENTID&client_secret=SECRET"
HEADERS = {
"Content-Type" => "application/x-www-form-urlencoded"
}
resp = Typhoeus::Request.post(url, body: params, headers: HEADERS)

I am following this link. Any clues why neither of curl / ruby works ? Thanks in advance

1

There are 1 answers

3
Peter Pan On

I tried to reproduce your issue successfully, and I discovered that the issue was caused by curl without OpenSSL and Typhoeus request without setting ssl_verifypeer: false.

So please follow this to check via curl --version and install openssl libraries on your environment.

Here is my sample code.

require "typhoeus"

url = 'https://login.microsoftonline.com/<tanet-id>/oauth2/token?api-version=1.0'
params = "grant_type=client_credentials&resource=https://management.core.windows.net/&client_id=<client-id>&client_secret=<client-key>"
headers = {
    "Content-Type" => "application/x-www-form-urlencoded"
}
request = Typhoeus.post(url, body: params, headers: headers, ssl_verifypeer: false)
puts request.code, request.body

Hope it helps.