Sample code for 30+ languages & platforms
Lua

Azure REST API Access Token

See more Azure OAuth2 Examples

Demonstrates how to request an Azure REST API OAUTH2 access token.

Note: In order to access resources a Service Principal needs to be created in your Tenant. It is really convenient to do it via AZ CLI:

az ad sp create-for-rbac --name [APP_NAME] --password [CLIENT_SECRET]

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.

local rest = chilkat.Rest.new()

-- URL: https://login.microsoftonline.com/TENANT_ID/oauth2/token
local bTls = true
local port = 443
local bAutoReconnect = true
local success = rest:connect("login.microsoftonline.com", port, bTls, bAutoReconnect)
if not success then
    print("ConnectFailReason: " .. rest.connect_fail_reason)
    print(rest.last_error_text)
    return
end

-- Add query params to the request.
rest:add_query_param("grant_type", "client_credentials")
rest:add_query_param("client_id", "APP_ID")
rest:add_query_param("client_secret", "CLIENT_SECRET")
-- Note: The resource must match the API for which you're using the access token..
rest:add_query_param("resource", "https://management.azure.com/")

local strResponseBody = rest:full_request_form_url_encoded("POST", "/TENANT_ID/oauth2/token")
if not rest.last_method_success then
    print(rest.last_error_text)
    return
end

local respStatusCode = rest.response_status_code
if respStatusCode >= 400 then
    print("Response Status Code = " .. respStatusCode)
    print("Response Header:")
    print(rest.response_header)
    print("Response Body:")
    print(strResponseBody)
    return
end

local json = chilkat.JsonObject.new()
json:load(strResponseBody)
json.emit_compact = false
print(json:emit())

-- The result is an access token such as the following:

-- {
--   "token_type": "Bearer",
--   "expires_in": "3600",
--   "ext_expires_in": "3600",
--   "expires_on": "1557864616",
--   "not_before": "1557860716",
--   "resource": "https://management.azure.com/",
--   "access_token": "eyJ0eXAiOiJKV1QiL ... 20UFDDOHEyUg"
-- }

-- We'll save this JSON to a file for other examples to use..
json:write_file("qa_data/tokens/azureToken.json")