I have a powershell script to insert a new redirect URI through powershell. If I run the commands one by one, it works whereas if I run the script with the parameters, it doesnt work. Please help.
This is my script.
#######################################################################################
#Create New Redirect URI in Azure App Service:
#######################################################################################
param
(
[string] $url,
[string] $objectId,
[string] $clientId,
[string] $tenantValue,
[string] $clientSecret,
[string] $serviceAccountEmail,
[string] $serviceAccountPassword
)
$webServiceURL = $url
Write-Host "$webServiceURL"
Write-Host "Done creating the webServiceURL"
Write-Host "Convert password to Secure string"
$SecurePassword = ConvertTo-SecureString $serviceAccountPassword -AsPlainText -Force
Write-Host "Done converting password to Secure string"
$Credential = New-Object System.Management.Automation.PSCredential($serviceAccountEmail, $SecurePassword)
Write-Host "Logging in"
Login-AzAccount -Credential $Credential
$tid = (Get-AzTenant).Id
Write-Host "Getting token"
$tokenBody = @{
'tenant' = $tid
'client_id' = $clientId
'scope' = 'https://graph.microsoft.com/.default'
'client_secret' = $clientSecret
'grant_type' = 'client_credentials'
}
$Params = @{
'Uri' = "https://login.microsoftonline.com/$tid/oauth2/v2.0/token"
'Method' = 'Post'
'Body' = $tokenBody
'ContentType' = 'application/x-www-form-urlencoded'
}
$AuthResponse = Invoke-RestMethod @Params
$AuthResponse
$header = @{
'Content-Type' = 'application/json'
'Authorization' = "Bearer $($AuthResponse.access_token)"
}
$header
$redirectUris = (Invoke-RestMethod -Method Get -Uri "https://graph.microsoft.com/beta/applications/$objectId" -Headers $header).spa.redirectUris
if ($redirectUris -notcontains "$webServiceURL") {
$redirectUris = "$webServiceURL"
Write-Host "Adding $webServiceURL to redirect URIs";
}
$body = @{
'spa' = @{
'redirectUris' = $redirectUris
}
} | ConvertTo-Json
Invoke-RestMethod -Method Patch -Uri "https://graph.microsoft.com/beta/applications/$objectId" -Headers $header -Body $body
Write-Host "Were there errors? (If the next line is blank, then no!) $error"
This is my screenshot where it is working if I enter commands step by step:
This is the screenshot where error occurs if I send it as parameters and execute the script file.
Do I need to wait on each step to get resolved and then proceed forward? Please advice.
CodePudding user response:
I tried to reproduce your issue by providing a wrong clientId, which is not a part of tenant I am logging into.
So as solution you have to pass correct clientId which is residing in your tenant for your code to succesfully run like below.
Update
Reproduce 403 forbidden error
Solution : Added API persmission-> Application.ReadWrite.All for Microsoft Graph under Application Permission.







