I’m trying to automate the process of creating an Azure AD application using Azure PowerShell. Specifically, I want to create an application, add a client secret, grant the Mail.Send permission, and generate a token, all within a single PowerShell script. However, I’m encountering a few challenges.
I was able to create the application successfully and add a client secret. However, I’m unsure how to add the Mail.Send Application permission to the application. I found the permission ID but don’t know the correct command to implement it.
Once the permission is added, do I need to grant admin consent explicitly, or is that handled automatically? I want to ensure everything is set up correctly before generating the token.
Here’s the code I’m working with:
Connect-AzAccount
$appName = "MyTestingApp"
$app = New-AzADApplication -DisplayName $appName -IdentifierUris "https://myapp.com"
$secret = New-AzADAppCredential -ApplicationId $app.ApplicationId -EndDate (Get-Date).AddYears(1)
$permissionId = "a0e0c2c0-6b4c-4c98-bcd8-15e7995d8f2b" # Mail.Send permission ID
$tenantId = "xxxxxxx"
$clientId = $app.ApplicationId
$clientSecret = $secret.SecretText
$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$body = @{
client_id = $clientId
client_secret = $clientSecret
scope = "https://graph.microsoft.com/.default"
grant_type = "client_credentials"
}
$response = Invoke-RestMethod -Method Post -Uri $tokenUrl -ContentType "application/x-www-form-urlencoded" -Body $body
$token = $response.access_token
2
Answers
Connect to Azure Account
Connect-AzAccount
Create the Azure AD application
$appName = "MyTestingApp"
$app = New-AzADApplication -DisplayName $appName -IdentifierUris "https://myapp.com"
Add a client secret
$secret = New-AzADAppCredential -ApplicationId $app.ApplicationId -EndDate (Get-Date).AddYears(1)
Define the permission ID for Mail.Send
$permissionId = "a0e0c2c0-6b4c-4c98-bcd8-15e7995d8f2b" # Mail.Send permission ID
Add the Mail.Send permission to the application
$resourceId = "00000003-0000-0000-c000-000000000000
You can make use of below sample PowerShell script to add
Mail.Send
permission when creating application with secret and generate token:Response:
To confirm that, I checked the same in Portal where new application with secret and permission added successfully with admin consent as below:
When I decoded the generated token in jwt.ms website, it has Mail.Send permission in
roles
claim like this: