Skip to content

Commit 6e2e8ff

Browse files
Add managed identity auth sample (Azure#24810)
* add managed identity sample * remove outputs
1 parent 8548d6c commit 6e2e8ff

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

sdk/ai/azopenai/example_azure_auth_methods_test.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,55 @@ func Example_usingDefaultAzureCredential() {
6161
makeSimpleRequest(&client, model)
6262
}
6363

64+
// Example_usingManagedIdentityCredential demonstrates how to authenticate with Azure OpenAI using Managed Identity.
65+
// This example shows how to:
66+
// - Create an Azure OpenAI client using ManagedIdentityCredential
67+
// - Support both system-assigned and user-assigned managed identities
68+
// - Make authenticated requests without storing credentials
69+
//
70+
// The example uses environment variables for configuration:
71+
// - AOAI_ENDPOINT: Your Azure OpenAI endpoint URL
72+
// - AOAI_MODEL: The deployment name of your model
73+
//
74+
// Managed Identity is ideal for:
75+
// - Azure services (VMs, App Service, Azure Functions, etc.)
76+
// - Azure DevOps pipelines with the Azure DevOps service connection
77+
// - CI/CD scenarios where you want to avoid storing secrets
78+
// - Production workloads requiring secure, credential-free authentication
79+
func Example_usingManagedIdentityCredential() {
80+
endpoint := os.Getenv("AOAI_ENDPOINT")
81+
model := os.Getenv("AOAI_MODEL")
82+
83+
if endpoint == "" || model == "" {
84+
fmt.Fprintf(os.Stderr, "Environment variables are not set, not running example.")
85+
return
86+
}
87+
88+
var credential *azidentity.ManagedIdentityCredential
89+
var err error
90+
91+
// Use system assigned managed identity
92+
credential, err = azidentity.NewManagedIdentityCredential(nil)
93+
94+
// When using User Assigned Managed Identity use this instead and pass your client id in the options
95+
// clientID := azidentity.ClientID("abcd1234-...")
96+
// opts := azidentity.ManagedIdentityCredentialOptions{ID: clientID}
97+
// cred, err := azidentity.NewManagedIdentityCredential(&opts)
98+
99+
if err != nil {
100+
fmt.Fprintf(os.Stderr, "ERROR: %s\n", err)
101+
return
102+
}
103+
104+
client := openai.NewClient(
105+
azure.WithEndpoint(endpoint, "2024-08-01-preview"),
106+
azure.WithTokenCredential(credential),
107+
)
108+
109+
// Use the client with managed identity credentials
110+
makeSimpleRequest(&client, model)
111+
}
112+
64113
// Helper function to make a simple request to Azure OpenAI
65114
func makeSimpleRequest(client *openai.Client, model string) {
66115
chatParams := openai.ChatCompletionNewParams{

0 commit comments

Comments
 (0)