Add a sample on how to use Workload Identity Credential. (#4894)

This commit is contained in:
Ahson Khan 2023-08-18 12:44:35 -07:00 committed by GitHub
parent 653d7dfecd
commit 66e36b0399
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 0 deletions

View File

@ -26,6 +26,11 @@ target_link_libraries(client_certificate_credential_sample PRIVATE azure-identit
target_include_directories(client_certificate_credential_sample PRIVATE .)
create_per_service_target_build_for_sample(identity client_certificate_credential_sample)
add_executable(workload_identity_credential_sample workload_identity_credential.cpp)
target_link_libraries(workload_identity_credential_sample PRIVATE azure-identity service get-env-helper)
target_include_directories(workload_identity_credential_sample PRIVATE .)
create_per_service_target_build_for_sample(identity workload_identity_credential_sample)
add_executable(client_secret_credential_sample client_secret_credential.cpp)
target_link_libraries(client_secret_credential_sample PRIVATE azure-identity service get-env-helper)
target_include_directories(client_secret_credential_sample PRIVATE .)

View File

@ -0,0 +1,42 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include <azure/identity/workload_identity_credential.hpp>
#include <azure/service/client.hpp>
#include <iostream>
// The following environment variables must be set before running the sample.
// * AZURE_TENANT_ID: Tenant ID for the Azure account.
// * AZURE_CLIENT_ID: The Client ID to authenticate the request.
// * AZURE_CLIENT_CERTIFICATE_PATH: The path to a client certificate.
std::string GetTenantId() { return std::getenv("AZURE_TENANT_ID"); }
std::string GetClientId() { return std::getenv("AZURE_CLIENT_ID"); }
std::string GetTokenFilePath() { return std::getenv("AZURE_FEDERATED_TOKEN_FILE"); }
int main()
{
try
{
// Step 1: Initialize Workload Identity Credential.
auto workloadIdentityCredential = std::make_shared<Azure::Identity::WorkloadIdentityCredential>(
GetTenantId(), GetClientId(), GetTokenFilePath());
// Step 2: Pass the credential to an Azure Service Client.
Azure::Service::Client azureServiceClient("serviceUrl", workloadIdentityCredential);
// Step 3: Start using the Azure Service Client.
azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext);
std::cout << "Success!" << std::endl;
}
catch (const Azure::Core::Credentials::AuthenticationException& exception)
{
// Step 4: Handle authentication errors, if needed
// (invalid credential parameters, insufficient permissions).
std::cout << "Authentication error: " << exception.what() << std::endl;
return 1;
}
return 0;
}