On Azure Portal we can grant Contributor role to Subscription using PIM for limited period of time.
Like 1 - 2 - 3 hours.
Those are called eligible assignments.
Anyone has tried assigning eligible assignments using powershell ?
As per my research -- AZureADPreview module is present.
(https://learn.microsoft.com/en-us/azure/active-directory/privileged-identity-management/powershell-for-azure-ad-roles )
But it is still under preview and doens't have full functionality.
I think the functionality has already been mentioned in the doc, give a sample here to elaborate on the specific usage.
For example, you want to assign the Application Administrator role to a user, then the script should be:
Note: The -ResourceId parameter uses your AAD tenant id <tenant-id>.
$role = Get-AzureADMSPrivilegedRoleDefinition -ProviderId aadRoles -ResourceId "<tenant-id>" | Where-Object {$_.DisplayName -eq 'Application Administrator'}
$schedule = New-Object Microsoft.Open.MSGraph.Model.AzureADMSPrivilegedSchedule
$schedule.Type = "Once"
$schedule.StartDateTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
$schedule.endDateTime = "2021-07-25T20:49:11.770Z"
Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId aadRoles -Schedule $schedule -ResourceId "<tenant-id>" -RoleDefinitionId $role.Id -SubjectId "<object-id of user or group>" -AssignmentState "Eligible" -Type "AdminAdd"
Check in the portal:
Related
I am preparing the report which contains all the users access level tenant wise from the azure.
is there any one command or script to get all the users access level from Azure tenant ?
That is a little be trick: The PS library for Azure is different from the PS library for the AD. You must cross informations.
You must get all users from you AD using the command above and save as variable
$allUsers = Get-ADUsers -Filter *
Now you can navigate to all subscriptions into your tenant, all resource groups and resources and for each and every one get the IAM (who came with the objectId of the user) and cross with the variable $allUsers to identify everyone.
The sample is not the best but maybe can help you:
Connect-AzAccount
$listIAM = New-Object System.Collections.ArrayList
$listSubscriptions = Get-AzSubscription
foreach($subscription in $listSubscriptions){
Set-AzContext -SubscriptionId $subscription.SubscriptionId
# Now you have all roleAssignements for this subscription
$subscriptionIAM = Get-AzRoleAssignment -Scope /subscriptions/$subscription.SubscriptionId
$listIAM.Add($subscriptionIAM) | Out-Null
# Navigate into resource groups
$listResourceGroups = Get-AzResourceGroup
foreach($resourceGroup in $listResourceGroups){
$rgIAM = Get-AzRoleAssignment -ResourceGroupName $resourceGroup.ResourceGroupName
$listIAM.Add($rgIAM) | Out-Null
# Navigate into resources
$listResources = Get-AzResource -ResourceGroupName $resourceGroup
foreach($resource in $listResources){
$rIAM = Get-AzRoleAssignment -Scope $resouce.ResourceId
$listIAM.Add($rIAM) | Out-Null
}
}
}
You can do this in either PowerShell or the Graph API. Both methods are in preview (the graph API calls are under the beta branch).
#Get the user
$userId = (Get-AzureADUser -Filter "userPrincipalName eq 'alice#contoso.com'").ObjectId
#Get direct role assignments to the user
$directRoles = (Get-AzureADMSRoleAssignment -Filter "principalId eq '$userId'").RoleDefinitionId
Prerequisites
AzureADPreview module when using PowerShell
Microsoft.Graph module when using PowerShell
Admin consent when using Graph Explorer for Microsoft Graph API
https://learn.microsoft.com/en-us/azure/active-directory/roles/list-role-assignments-users
I have Azure AD App role assignments to groups in an environment that I can only access using Powershell. To get the AD APP roles assigned to a particular AD Group, I used the command Get-AzureADGroupAppRoleAssignment -ObjectId XXXX-XXX... where the objectId here is the group object id, which works, but the problem is that the output of the command shows only the objectId of the App role, and that objectId isn't for some reason a valid GUID, which makes me unable to use it to query the name of the app role.
Please see below snapshot
To query the name of the app role, you could use the command below.
$rs = Get-AzureADGroupAppRoleAssignment -ObjectId <object-id>
foreach($r in $rs){
$app = Get-AzureADServicePrincipal -ObjectId $r.ResourceId
$DisplayName = ($app.AppRoles | Where-Object {$_.Id -eq $r.Id}).DisplayName
Write-Host $DisplayName of $app.AppDisplayName
}
Its simple, you need to filter your app role with the display name in Get-AzureADGroup and pass it to Get-AzureADGroupAppRoleAssignment
$GroupId = (Get-AzureADGroup -Filter "DisplayName eq 'displayname'" -top 1).objectid
Get-AzureADGroupAppRoleAssignment -ObjectId $GroupId
For reporting and monitoring purpose do I like to retrieve the information shown in the Azure portal for an application (App Registration) for "API permissions".
I have tried the following code
$app = Get-AzureADApplication -ObjectId 'aa7e174d-2639-4ac7-9b11-6799466c3c9b'
$app.Oauth2Permissions
But this yields only the following information:
AdminConsentDescription : Allow the application to access foobar_HVV on behalf of the signed-in user.
AdminConsentDisplayName : Access foobar_HVV
Id : h1285f9d5-b00d-4bdb-979d-c4d6487fa000
IsEnabled : True
Type : User
UserConsentDescription : Allow the application to access foobar_HVV on your behalf.
UserConsentDisplayName : Access foobar_HVV
Value : user_impersonation
But "API Permissions" for the application "foobar_HVV" shows totally different permissions. Especially the "Typ" (Delegate, Application) and the "Status" per permission are needed for my report.
If you want to get the API permissions, you need to use the command below.
$app = Get-AzureADApplication -ObjectId '<object-id of the App Registration>'
$app.requiredResourceAccess | ConvertTo-Json -Depth 3
The ResourceAppId is the Application ID of the service principal of the API e.g. Microsoft Graph, the ResourceAccess includes the permissions you added to the app, the Scope means the Delegated permission, Role means the Application permission.
My API permissions:
To check the details of the API permissions , you need to use the command below. For example, we want to know the details of the permission whose Id is 5b567255-7703-4780-807c-7be8301ae99b in the screenshot, its Type is Role, so we need to use $sp.AppRoles.
$sp = Get-AzureADServicePrincipal -All $true | Where-Object {$_.AppId -eq '00000003-0000-0000-c000-000000000000'}
$sp.AppRoles | Where-Object {$_.Id -eq '5b567255-7703-4780-807c-7be8301ae99b'}
If you want to get the Delegated permission(Type is Scope), we need to use:
$sp = Get-AzureADServicePrincipal -All $true | Where-Object {$_.AppId -eq '00000003-0000-0000-c000-000000000000'}
$sp.Oauth2Permissions | Where-Object {$_.Id -eq 'e1fe6dd8-ba31-4d61-89e7-88639da4683d'}
To check Status, there is no direct way, you need to check the permissions granted by the admin of the service principal corresponds to the AD App in your AAD tenant.
First, get the service principal $appsp:
$app = Get-AzureADApplication -ObjectId '<object-id of the App Registration>'
$appsp = Get-AzureADServicePrincipal -All $true | Where-Object {$_.AppId -eq $app.AppId}
Get the Delegated permissions which has been granted(Status is Granted):
Get-AzureADServicePrincipalOAuth2PermissionGrant -ObjectId $appsp.ObjectId -All $true | ConvertTo-Json
The ResourceId is the Object Id of the service principal of the API:
Get the Application permissions which has been granted(Status is Granted):
Get-AzureADServiceAppRoleAssignedTo -ObjectId $appsp.ObjectId | ConvertTo-Json
The Id is the Id in the ResourceAccess in the first screenshot.
If the permission has not been granted(Status is Not Granted), you will not get the permission with the command above.
For example, I add a new Application permission in the portal, then run the command again, we can still get the permission which has been granted.
Looking after a new Solution using the 7.1 PowerShell and Az Client I've wrote follwing Script to solve this Issue:
# loop in all Applications then every Application Loop this one to
$sp = $sp = az ad app list --display-name "yourapplication"
$spIdList = ($sp |ConvertFrom-Json -AsHashtable).requiredResourceAccess.resourceAccess
# retreive the ID from Bucket
$RoleAppID = ($sp| ConvertFrom-Json ).requiredResourceAccess.resourceAppId
## receive all Roles and lookup inside
$appRolesArray = (az ad sp show --id $RoleAppID | ConvertFrom-Json -AsHashtable ).appRoles
$listRoles = #()
foreach ($itemSpId in $spIdList) {
$itemSpId.id
foreach($item in $appRolesArray ) {
if ( $item.id -eq $itemSpId.id ){
$listRoles += $item
$item
}
}
}
$listRoles.count
now you can do whatever you want with the List of those objects.
The Goal was to use the "az client"
I am new to Exchange Online, and Azure, but Ive been asked if we can create O365 groups in Exchange Online, using the New-UnifiedGroup and Set-UnifiedGroup cmdlets. Then they want to be able to make those groups dynamic, based upon certain criteria. Is this even possible, or do I skip Exchange Online entirely, and in Azure use the New-AzureADMSGroup cmdlets to create a dynamic group.
Any help is appreciated.
Thanks.
Yes, you could create an Office 365 group with AzureAD PowerShell cmdlet New-AzureADMSGroup and you need to install AzureAD module first.
For example, This command creates a new dynamic group with the following rule:
user.department -contains "Marketing"
The double quotation marks are replaced with single quotation marks.
The processing state is On. This means that all users in the directory
that qualify the rule are added as members to the group. Any users
that do not qualify are removed from the group.
New-AzureADMSGroup -DisplayName "Dynamic Group 01" -Description "Dynamic group created from PS" -MailEnabled $False -MailNickName "group" -SecurityEnabled $True -GroupTypes "DynamicMembership" -MembershipRule "(user.department -contains ""Marketing"")" -MembershipRuleProcessingState "On"
More references: https://techcommunity.microsoft.com/t5/Azure-Active-Directory-Identity/New-enhancements-to-the-AzureAD-PowerShell-2-0-preview-Manage/ba-p/245153
and https://blog.hubfly.com/office-365/useful-powershell-cmdlets-to-administer-office-365-groups-part-1
Ok, so here is the solution we came up with.
Requires AzureADPreview module, current version as of today 2.0.2.17
The AzureAD Module wont work, as it is missing parameters required for group membership.
Requires a Connection into AzureAD, and also Exchange Online.
The account you connect with need to be an Exchange Administrator in Exchange Online, and an User Administrator in AzureAD.
In our example we want an Office group, that is dynamic, and the membershipRule based upon extensionattribute12.
#***********************************************************************
$ADUser = "samAccountName#yourdomain"
$ADPassword = 'the password'
$ADPwd = $ADPassword | ConvertTo-SecureString -AsPlainText -Force
$UserCredential = new-object system.management.automation.pscredential $ADuser, $ADPwd
#***********************************************************************
"Connect AzureAD"
Connect-AzureAD -Credential $UserCredential
"Connect to Exchange Online"
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking
#######################################
function ConvertStaticGroupToDynamic
{
Param([string]$groupId, [string]$dynamicMembershipRule)
$dynamicGroupTypeString = "DynamicMembership"
#existing group types
[System.Collections.ArrayList]$groupTypes = (Get-AzureAdMsGroup -Id $groupId).GroupTypes
if($groupTypes -ne $null -and $groupTypes.Contains($dynamicGroupTypeString))
{
throw "This group is already a dynamic group. Aborting conversion.";
}
#add the dynamic group type to existing types
$groupTypes.Add($dynamicGroupTypeString)
#modify the group properties to make it a static group: i) change GroupTypes to add the dynamic type, ii) start execution of the rule, iii) set the rule
Set-AzureAdMsGroup -Id $groupId -GroupTypes $groupTypes.ToArray() -MembershipRuleProcessingState "On" -MembershipRule $dynamicMembershipRule
}
#######################################
$ExtAtt12 = "Marketing"
$NewGroupName = "O365-OfficeGroupTest"
"[$NewGroupName] create group"
New-UnifiedGroup -DisplayName $NewGroupName
Set-UnifiedGroup $NewGroupName -UnifiedGroupWelcomeMessageEnabled:$false
$ID = (Get-UnifiedGroup $NewGroupName).ExternalDirectoryObjectId
sleep 15 # Allow time for Exchange Online to Sync with AzureAD
ConvertStaticGroupToDynamic -groupId $ID -dynamicMembershipRule "(User.extensionattribute12 -eq ""$ExtAtt12"")"
We have two azure resources in the same directory. A webAPI set of APIs behind Azure API Management and an Azure Function. We want the azure function to be able to call the APIs. We've enabled MSI on the azure function as described in How to use managed identities for App Service and Azure Functions. We've created an App Registration in AAD for the API, created a role permission to be accessed. Following Calling your APIs with Azure AD Managed Service Identity using application permissions we run into errors attempting to assign the permission/role to the azure function:
in powershell:
New-AzureADServiceAppRoleAssignment -ObjectId 8XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX -Id 3XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX -PrincipalId 8XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX -ResourceId 9XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
New-AzureADServiceAppRoleAssignment : Error occurred while executing NewServicePrincipalAppRoleAssignment
Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation.
HttpStatusCode: Forbidden
HttpStatusDescription: Forbidden
HttpResponseStatus: Completed
At line:1 char:1
+ New-AzureADServiceAppRoleAssignment -ObjectId 8XXXXXX-XXXX-XXXX-XXXX ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-AzureADServiceAppRoleAssignment], ApiException
+ FullyQualifiedErrorId : Microsoft.Open.AzureAD16.Client.ApiException,Microsoft.Open.AzureAD16.PowerShell.NewServ
icePrincipalAppRoleAssignment
is giving us a permission error, even when an AAD Admin (member of AAD DC Administrators I think) runs it. Has anyone run into this before? Why is this throwing a permissions error? We have verified that the ids are correct with 3 different people.
The problem you're probably facing is that, despite naming your app registration the same thing as your MSI-enabled app, the two end up representing different service principals in AAD. Using app registrations with MSI isn't currently supported.
Try running the powershell commands using the object id of the MSI identity instead. I was able to get this to work, and granted my MSI-enabled app access to the Graph Api.
Here is the PS I used to assign the GraphApi roles my function app required:
$functionAppName = "My-FANCY-FUNC"
$context = Get-AzureRmContext -ErrorAction SilentlyContinue #this lets you search AAD for func
if(!$context){
$login = Connect-AzureRmAccount | Out-Null
Connect-AzureAD #needed this for Graph API
$context = $login
} else { Write-Host "Login session already established for " $context.Subscription.SubscriptionName }
#get the SP associated with the MSI
$MSIPrincipal = Get-AzureRmADServicePrincipal -SearchString $functionAppName | Where-Object DisplayName -eq $functionAppName
#get the SP associatesd with the MS Graph
$graph = Get-AzureADServicePrincipal -All $true | ? { $_.DisplayName -match "Microsoft Graph" }
#find the target app roles in the graph
$targetRoles = $graph.AppRoles | Where-Object Value -in "Group.ReadWrite.All", "Directory.ReadWrite.All"
#iterate throgh the known roles and add the MSI SP to them
$targetRoles | ForEach-Object {New-AzureADServiceAppRoleAssignment -Id $_.Id -PrincipalId $MSIPrincipal.Id -ObjectId $MSIPrincipal.Id -ResourceId $graph.ObjectId}
I suspect, based on your question, that this line will return more than one entity:
Get-AzureRmADServicePrincipal -SearchString $functionAppName | Where-Object DisplayName -eq $functionAppName
Deleting your extraneous app registration should clear that up