|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +#include <azure/identity/workload_identity_credential.hpp> |
| 5 | +#include <azure/service/client.hpp> |
| 6 | + |
| 7 | +#include <iostream> |
| 8 | + |
| 9 | +// The following environment variables must be set before running the sample. |
| 10 | +// * AZURE_TENANT_ID: Tenant ID for the Azure account. |
| 11 | +// * AZURE_CLIENT_ID: The Client ID to authenticate the request. |
| 12 | +// * AZURE_CLIENT_CERTIFICATE_PATH: The path to a client certificate. |
| 13 | +std::string GetTenantId() { return std::getenv("AZURE_TENANT_ID"); } |
| 14 | +std::string GetClientId() { return std::getenv("AZURE_CLIENT_ID"); } |
| 15 | +std::string GetTokenFilePath() { return std::getenv("AZURE_FEDERATED_TOKEN_FILE"); } |
| 16 | + |
| 17 | +int main() |
| 18 | +{ |
| 19 | + try |
| 20 | + { |
| 21 | + // Step 1: Initialize Workload Identity Credential. |
| 22 | + auto workloadIdentityCredential = std::make_shared<Azure::Identity::WorkloadIdentityCredential>( |
| 23 | + GetTenantId(), GetClientId(), GetTokenFilePath()); |
| 24 | + |
| 25 | + // Step 2: Pass the credential to an Azure Service Client. |
| 26 | + Azure::Service::Client azureServiceClient("serviceUrl", workloadIdentityCredential); |
| 27 | + |
| 28 | + // Step 3: Start using the Azure Service Client. |
| 29 | + azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); |
| 30 | + |
| 31 | + std::cout << "Success!" << std::endl; |
| 32 | + } |
| 33 | + catch (const Azure::Core::Credentials::AuthenticationException& exception) |
| 34 | + { |
| 35 | + // Step 4: Handle authentication errors, if needed |
| 36 | + // (invalid credential parameters, insufficient permissions). |
| 37 | + std::cout << "Authentication error: " << exception.what() << std::endl; |
| 38 | + return 1; |
| 39 | + } |
| 40 | + |
| 41 | + return 0; |
| 42 | +} |
0 commit comments