-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnectToMSGraphWithMIandKeyVault2.ps1
31 lines (25 loc) · 1.33 KB
/
ConnectToMSGraphWithMIandKeyVault2.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Connect to Azure using af Managed Identity (VM)
Connect-AzAccount -Identity
$KeyVaultName = "" # The name of your Azure Key Vault
$KeyVaultSecretName = "" # The name of the Secret entry in the Azure Key Vault
$KeyVaultTenantIDName = "" # The name of the TenantID entry in the Azure Key Vault
$KeyVaultClientIDName = "" # The name of the ClientID entry in the Azure Key Vault
# Fetch the values from the Azure Key vault
$KeyVaultSecret = Get-AzKeyVaultSecret -VaultName $KeyVaultName -Name $KeyVaultSecretName -AsPlainText
$KeyVaultTenantID = Get-AzKeyVaultSecret -VaultName $KeyVaultName -Name $KeyVaultTenantIDName -AsPlainText
$KeyVaultClientID = Get-AzKeyVaultSecret -VaultName $KeyVaultName -Name $KeyVaultClientIDName -AsPlainText
# Connect to the Microsoft Graph with the Service Principal usinge the values from the Azure Key vault
$body = @{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
Client_Id = $KeyVaultClientID
Client_Secret = $KeyVaultSecret
}
$connection = Invoke-RestMethod `
-Uri https://login.microsoftonline.com/$KeyVaultTenantID/oauth2/v2.0/token `
-Method POST `
-Body $body
$GraphToken = ConvertTo-SecureString $connection.access_token -AsPlainText -Force
Connect-MgGraph -AccessToken $GraphToken -Verbose
# Get users from the Graph
Get-MgUser