I am trying to call the Graph API to add a user to the Azure AD group, but it shows me a bad request.
I have the script and it looks for me that it should work, but it shows be a bad request. Other calls work perfect, and I have all the permissions in Azure AD for the app registration.
function AddUserToGroup {
param (
[string] $TenantId,
[string] $GroupId,
[string] $UserId,
[string] $ClientId,
[string] $ClientSecret
)
try {
# Azure AD token endpoint
$tokenEndpoint = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
# Azure AD API endpoint to add members to the group
$apiEndpoint = "https://graph.microsoft.com/v1.0/groups/$GroupId/members/$ref"
# Request access token
$tokenBody = @{
client_id = $ClientId
client_secret = $ClientSecret
grant_type = "client_credentials"
scope = "https://graph.microsoft.com/.default"
}
$tokenResponse = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -Body $tokenBody
$accessToken = $tokenResponse.access_token
# Construct the request body
# Create the hashtable representing the JSON content
$body = @{
"@odata.id" = "https://graph.microsoft.com/v1.0/directoryObjects/$userId"
}
$headers = @{
Authorization = "Bearer $accessToken"
"Content-Type" = "application/json"
}
# Add the user to the group
$response = Invoke-RestMethod -Method Post -Uri $apiEndpoint -Headers $headers -Body ($body | ConvertTo-Json)
Write-Host "Added user with ID $UserId to the group."
}
catch {
Write-Host "An error occurred while adding user with ID $UserId to the group: $($_.Exception.Message)"
if ($_.Exception.Response) {
$errorResponse = $_.Exception.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd()
Write-Host "Detailed error response: $responseBody"
}
}
}
# Usage:
$tenantId = ""
$groupId = ""
$userId = ""
$clientId = ""
$clientSecret = ""
AddUserToGroup -TenantId $tenantId -GroupId $groupId -UserId $userId -ClientId $clientId -ClientSecret $clientSecret
Turns out PowerShell is converting $ref to "", Always a bummer, seen and debugged many times. You script is okay.
Just replace the API Endpoint with something like below to preserve $ref in the Graph API endpoint called. Apparently single quotes will not try to treat $ref as a variable reference.
# Azure AD API endpoint to add members to the group
$apiEndpoint = "https://graph.microsoft.com/v1.0/groups/$GroupId/members/`$ref"