Sample code for 30+ languages & platforms
Zig

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 Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

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

    const rest = try chilkat.Rest.init();
    defer rest.deinit();

    // URL: https://login.microsoftonline.com/TENANT_ID/oauth2/token
    const b_tls = true;
    const port = 443;
    const b_auto_reconnect = true;
    rest.connect("login.microsoftonline.com", port, b_tls, b_auto_reconnect) catch {
        std.debug.print("ConnectFailReason: {d}\n", .{rest.getConnectFailReason()});
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

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

    const str_response_body = rest.fullRequestFormUrlEncoded(alloc, "POST", "/TENANT_ID/oauth2/token") catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    const resp_status_code = rest.getResponseStatusCode();
    if (resp_status_code >= 400) {
        std.debug.print("Response Status Code = {d}\n", .{resp_status_code});
        std.debug.print("Response Header:\n", .{});
        std.debug.print("{s}\n", .{try rest.getResponseHeader(alloc)});
        std.debug.print("Response Body:\n", .{});
        std.debug.print("{s}\n", .{str_response_body});
        return;
    }

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.load(str_response_body) catch {};
    json.setEmitCompact(false);
    std.debug.print("{s}\n", .{try json.emit(alloc)});

    // 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.writeFile("qa_data/tokens/azureToken.json") catch {};
}