How to add app role to using powershell to service principal

Brass Contributor

Hi All,

 

I would like to add app roles to my service principal in Azure AD.

 

1 Reply

@Sagar_Lad ,

 

[CmdletBinding()]
Param
(
    [Parameter(Mandatory = $true)][string]$AppName,
    [Parameter(Mandatory = $true)][string]$token,
    [Parameter(Mandatory = $true)][string[]] $AllowedMemberTypes
)

try {


 #Connect-AzureAD
 Install-Module -Name AzureAD -Scope CurrentUser -Force
    
 $currentAzureContext = Get-AzContext
 $tenantId = $currentAzureContext.Tenant.Id
 $accountId = $currentAzureContext.Account.Id
 Connect-AzureAD -AadAccessToken $token -AccountId $accountId -TenantId $tenantId

# Create an application role of given name and description

$Id = [Guid]::NewGuid().ToString()

# Create new AppRole object
$newAppRole = [Microsoft.Open.AzureAD.Model.AppRole]::new()
$newAppRole.AllowedMemberTypes = New-Object System.Collections.Generic.List[string]
$newAppRole.AllowedMemberTypes.Add("User")
$newAppRole.DisplayName = "User"
$newAppRole.Description = "User Role"
$newAppRole.Value = "User"
$newAppRole.Id = $Id
$newAppRole.IsEnabled = $true

# Add new AppRole and apply changes to Application object

$App = Get-AzureADServicePrincipal -Filter "displayName eq '$AppName'"
$appRoles = $App.AppRoles | Where-Object { $_.DisplayName -eq $RoleToAssign }
echo $appRoles
$SPNObjectId=(Get-AzADServicePrincipal -DisplayNameBeginsWith $AppName).Id
echo $SPNObjectId

$appRoles += $newAppRole
echo $appRoles

Set-AzureADApplication -ObjectId $SPNObjectId -AppRoles $appRoles

}  

catch {
    $message = $Error[0].Exception.Message
    Write-Host "##vso[task.logissue type=error;]$message.";
    Write-Error $message;
}