我正在尝试编写一个 PowerShell 脚本来创建一个 azure AD 应用程序和该应用程序的客户端 key 。最后:代码应该打印 App-ID、租户 ID 和客户端 key 的值: 这是我编写的代码:
# Function to generate a random password
function Generate-Password {
$validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+"
$password = ""
For ($i=0; $i -lt 16; $i++) {
$random = Get-Random -Minimum 0 -Maximum $validChars.Length
$password += $validChars[$random]
}
return $password
}
# Authenticate and login to Azure
Connect-AzAccount
# Set the name, home page URL, and identifier URI of the app
$appName = "test-123"
# Generate a random password for the client secret
$clientSecretPassword = Generate-Password | ConvertTo-SecureString -AsPlainText -Force
# Create the Azure AD app
$app = New-AzADApplication -DisplayName $appName
# Create a client secret for the app
$secret = New-AzADAppCredential -ApplicationId $app.ApplicationId -Password $clientSecretPassword
$secret.Secret
# Print the Client ID and Tenant ID of the app
Write-Host "Client ID: " $app.ApplicationId
Write-Host "Tenant ID: " (Get-AzContext).Tenant.Id
# Print the value of the client secret
$clientsecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secret.Secret))
Write-Host "Client Secret: " $clientSecret
但我收到以下错误:
Exception calling "SecureStringToBSTR" with "1" argument(s): "Value cannot be null.
Parameter name: s"
At C:\Users\azure-app.ps1:35 char:1
+ $clientsecret = [System.Runtime.InteropServices.Marshal]::PtrToStrin ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
Client Secret:
任何人都可以帮我调试这个问题或重构代码吗? 谢谢
最佳答案
我尝试在我的环境中重现相同的内容,以创建 azure AD 应用程序并使用 PowerShell 显示客户端 key 和客户端 ID
您可以使用以下PowerShell脚本使用客户端 key 创建Azure AP应用程序。
#Connect to Azure AD
Connect-AzureAD
#Set variables for the app
$appName = "MyApp"
$replyUrls = "http://localhost"
$secret = "MySecret"
#Create the app
$app = New-AzureADApplication -DisplayName $appName -ReplyUrls $replyUrls -PublicClient $false
#Create the client secret
$bytes = [System.Text.Encoding]::Unicode.GetBytes($secret)
$base64 = [System.Convert]::ToBase64String($bytes)
$startDate = Get-Date
$endDate = $startDate.AddYears(1)
$secret = New-AzureADApplicationPasswordCredential -ObjectId $app.ObjectId -CustomKeyIdentifier "MyCustomKeyIdentifier" -Value $base64 -StartDate $startDate -EndDate $endDate
#Retrieve the tenant ID
$tenantId = (Get-AzureADTenantDetail).ObjectId
#Print the App-ID, tenant ID, and client secret
Write-Host "App-ID: $($app.AppId)"
Write-Host "Tenant ID: $tenantId"
Write-Host "Client Secret: $($secret.Value)"
运行上述命令后,使用客户端 key 成功创建了Azure应用程序。
当我在门户中检查Azure App时,它已成功创建。
关于azure - 使用 az powershell 创建 Azure AD 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75605531/