Skip to content

Instantly share code, notes, and snippets.

@AlexanderHolmeset
Last active February 9, 2023 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexanderHolmeset/43489f02709a286f6685831ccef75b9b to your computer and use it in GitHub Desktop.
Save AlexanderHolmeset/43489f02709a286f6685831ccef75b9b to your computer and use it in GitHub Desktop.
function Get-AzureOpenAIToken{
<# .SYNOPSIS
Get an azure token for user or managed identity thats required to authenticate to Azure OpenAI with Rest API.
Also construct the header if you are using an Azure OpenAI API key instead of Azure AD authentication.
.PARAMETER ManagedIdentity
Use this parameter if you want to use a managed identity to authenticate to Azure OpenAI.
.PARAMETER User
Use this parameter if you want to use a user to authenticate to Azure OpenAI.
.PARAMETER APIKey
Use this parameter if you want to use an API key to authenticate to Azure OpenAI.
.EXAMPLE
# Manually specify username and password to acquire an authentication token:
Get-AzureOpenAIToken -APIKey "ghgkfhgfgfgkhgh"
Get-AzureOpenAIToken -ManagedIdentity $true
Get-AzureOpenAIToken -User $true
.NOTES
Author: Alexander Holmeset
Twitter: @AlexHolmeset
Website: https://www.alexholmeset.blog
Created: 09-02-2023
Updated:
Version history:
1.0.0 - (09-02-2023) Function created
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)]
[string]$APIKey,
[Parameter(Mandatory=$false)]
[string]$ManagedIdentity,
[Parameter(Mandatory=$false)]
[string]$User
)
Process {
$ErrorActionPreference = "Stop"
if (Get-Module -ListAvailable -Name Az.Accounts) {
# Write-Host "You have the Az.Accounts module installed"
}
else {
Write-Host "You need to install the Az.Accounts module";
break
}
If(!$MyHeader){
If($ManagedIdentity -eq $true){
"managed"
try {
Connect-AzAccount -Identity
$MyTokenRequest = Get-AzAccessToken -ResourceUrl "https://cognitiveservices.azure.com"
$MyToken = $MyTokenRequest.token
If(!$MyToken){
Write-Warning "Failed to get API access token!"
Exit 1
}
$Global:MyHeader = @{"Authorization" = "Bearer $MyToken" }
}
catch [System.Exception] {
Write-Warning "Failed to get Access Token, Error message: $($_.Exception.Message)"; break
}
}
If($User -eq $true){
"USER"
try {
Connect-AzAccount
$MyTokenRequest = Get-AzAccessToken -ResourceUrl "https://cognitiveservices.azure.com"
$MyToken = $MyTokenRequest.token
If(!$MyToken){
Write-Warning "Failed to get API access token!"
Exit 1
}
$Global:MyHeader = @{"Authorization" = "Bearer $MyToken" }
}
catch [System.Exception] {
Write-Warning "Failed to get Access Token, Error message: $($_.Exception.Message)"; break
}
}
If($APIkey){
"APIKEY"
$Global:MyHeader = @{"api-key" = $apikey }
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment