Sample code for 30+ languages & platforms
Rust

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

Rust

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

let rest = chilkat::Rest::new();

// URL: https://login.microsoftonline.com/TENANT_ID/oauth2/token
let b_tls = true;
let port = 443;
let b_auto_reconnect = true;
if rest.connect("login.microsoftonline.com", port, b_tls, b_auto_reconnect).is_err() {
    println!("ConnectFailReason: {}", rest.connect_fail_reason());
    println!("{}", rest.last_error_text());
    return;
}

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

let Ok(str_response_body) = rest.full_request_form_url_encoded("POST", "/TENANT_ID/oauth2/token") else {
    println!("{}", rest.last_error_text());
    return;
};

let resp_status_code = rest.response_status_code();
if resp_status_code >= 400 {
    println!("Response Status Code = {}", resp_status_code);
    println!("Response Header:");
    println!("{}", rest.response_header());
    println!("Response Body:");
    println!("{}", str_response_body);
    return;
}

let json = chilkat::JsonObject::new();
let _ = json.load(&str_response_body);
json.set_emit_compact(false);
println!("{}", json.emit().unwrap_or_default());

// 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..
let _ = json.write_file("qa_data/tokens/azureToken.json");