Sample code for 30+ languages & platforms
Rust Requires Chilkat v11.0.0+

Azure OAuth2 Client Credentials Grant Flow

See more OAuth2 Examples

Demonstrates how to get an OAuth2 access token for an Azure Registered App using the Client Credentials Grant Flow.

Note: Your Azure app must be registered as a single-tenant app to use client credentials.

Chilkat Rust Downloads

Rust

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

let http = chilkat::Http::new();

let req = chilkat::HttpRequest::new();
req.add_param("client_secret", "CLIENT_SECRET");
req.add_param("client_id", "CLIENT_ID");

// See Understanding Scopes in Azure OAuth2 Client Credentials Flow
req.add_param("scope", "https://graph.microsoft.com/.default");

req.add_param("grant_type", "client_credentials");

// Note: Your Azure app must be registered as a single-tenant app to use client credentials.
// Use your own tenant ID, for example 4d8fdd66-66d1-43b0-ae5c-e31b4b7de5cd
let url = "https://login.microsoftonline.com/TENANT_ID/oauth2/v2.0/token".to_string();

req.set_http_verb("POST");
req.set_content_type("application/x-www-form-urlencoded");

let resp = chilkat::HttpResponse::new();
if http.http_req(&url, &req, &resp).is_err() {
    println!("{}", http.last_error_text());
    return;
}

let status_code = resp.status_code();
println!("Response status code = {}", status_code);

let json = chilkat::JsonObject::new();
let _ = json.load(&resp.body_str());

json.set_emit_compact(false);
println!("{}", json.emit().unwrap_or_default());

// Sample successful output:

// {
//   "token_type": "Bearer",
//   "expires_in": 3599,
//   "ext_expires_in": 3599,
//   "access_token": "eyJ0eX...K0jOERg"
// }

if status_code == 200 {
    let _ = json.write_file("qa_data/tokens/azureClientCredentialsToken.json");
    println!("Success.");
} else {
    println!("Failed.");
}