To use Azure Managed Identity to send emails using the Microsoft Graph API without hard-coding the client secret, you can modify your PowerShell script to authenticate using the Managed Identity instead of using client credentials. Here’s how you can update your code:
- Remove Client Secret and Client ID: Since you are using Managed Identity, you do not need to specify the
ClientIdandclientSecret. - Get Access Token Using Managed Identity: You can obtain an access token for Microsoft Graph using the Managed Identity directly. Here’s how you can do that:
# Get an access token using Managed Identity
$tokenUri = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://graph.microsoft.com/"
$response = Invoke-RestMethod -Method Get -Uri $tokenUri -Headers @{ Metadata = "true" }
$token = $response.access_token
if (-not $token) {
Write-Output "Failed to retrieve access token. Check your Managed Identity configuration."
exit 1
}
Write-Output $token
- Update Email Sending Logic: The rest of your email sending logic can remain largely the same, but you will use the
$tokenobtained from the Managed Identity for authorization.
Here’s the updated portion of your script:
# Send the email using Microsoft Graph API
$sendEmailUri = "https://graph.microsoft.com/v1.0/users/$senderEmail/sendMail"
Invoke-RestMethod -Uri $sendEmailUri -Method POST -Headers @{ Authorization = "Bearer $token" } -Body ($emailMessage | ConvertTo-Json -Depth 10) -ContentType "application/json"
Write-Output "Notification email sent."
- Assign Required Permissions: Ensure that the Managed Identity has the necessary permissions in Azure AD for
Mail.Send,Application.Read.All, andDirectory.Read.All. You can assign these permissions through the Azure portal or using PowerShell.
By following these steps, you can effectively use Azure Managed Identity to send emails without hard-coding sensitive information in your script.