2025-03-04

Create Microsoft Entra Application Service Principal for Connect-AzAccount

在 PowerShell 中用帳號密碼進行 Connect-AzAccount 會被罵

WARNING: Authentication with a username and password at the command line is strongly discouraged. Use one of the recommended authentication methods based on your requirements. For additional information, visit https://go.microsoft.com/fwlink/?linkid=2276971.

先用具有適當權限的帳號登入後用以下 Script 建立 Service Principal Application
再到 RBAC 賦予需要的權限

Set-Location -LiteralPath 'C:\Command\AzureConnect';

$AzureEntraTenantId = 'xxxxxxxx-xxxx-xxxx-xx-xxxxxxxxxxxx';
$AzSubscriptionID = 'xxxxxxxx-xxxx-xxxx-xx-xxxxxxxxxxxx';
$ServicePrincipalName = 'PowershellAutomaticProcess';
$CredentailFileName = ('AzConnect_' + $ServicePrincipalName + '.txt')
$CertificateExpired = 100;
#設定密碼 100 年後到期 (預設 1 年),往下找 AddYears 字串那邊可以改

if ((Test-Path -LiteralPath $CredentailFileName) -eq $True) {
    [string[]]$CredentialRead = Get-Content -Path $CredentailFileName;
    $UserName = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($CredentialRead[0]));
    $Password = $CredentialRead[1] | ConvertTo-SecureString;
} else {
    $App = New-AzADServicePrincipal -DisplayName $ServicePrincipalName;

    $passwordCredential = New-Object -TypeName 'Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphPasswordCredential';
    $passwordCredential.DisplayName = ('Token_For_' + $ServicePrincipalName);
    $passwordCredential.EndDateTime = [DateTime]::Now.AddYears($CertificateExpired);

    $AppCredential = New-AzADAppCredential -ApplicationId $App.AppId -PasswordCredential $passwordCredential;

    Get-AzADAppCredential -ApplicationId $App.AppId | where {$_.KeyId -ne $AppCredential.KeyId} | foreach {
        Remove-AzADAppCredential -ApplicationId $App.AppId -KeyId $_.KeyId;
    };
    
    $UserName = [string]$App.AppId
    $Password = (ConvertTo-SecureString -String $AppCredential.SecretText -AsPlainText -Force);
    
    $EncodedAppID = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($UserName));
    $EncryptedPassWord = ConvertFrom-SecureString -SecureString $Password;
    ($EncodedAppID + "`r`n" + $EncryptedPassWord) | Set-Content $CredentailFileName;
};

$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserName, $Password;
$ConnectAzAccount = Connect-AzAccount -ServicePrincipal -Credential $Credential -Tenant $AzureEntraTenantId;
Select-AzSubscription -SubscriptionId $AzSubscriptionID | Out-Null;

Get-AzADServicePrincipal -DisplayName $ServicePrincipalName;


沒有留言:

張貼留言