Insufficient privileges to complete the operation while invoking Get-AzADGroupMember - azure

I have an Azure function in Powershell(v 2.0) with Az Module Installed and an assigned managed identity to manage resources within a bunch of subscriptions for a tenant say 'A'. Because of which I have been able to perform operations to handle VM/subscriptions management with commands like Get-AzVm, Set-AzContext etc.
In the function, there is a logic to check if a user is present within an Usergroup say 'readonlygroup' in AzureAD for tenant 'A'. And I'm trying to get the usergroup from the function by calling
$users = Get-AzADGroupMember -GroupDisplayName 'readonlygroup'
But I get an exception thrown
ERROR: Get-AzADGroupMember : Insufficient privileges to complete the operation.
At D:\home\site\wwwroot\{functionname}\run.ps1:110 char:18
+ ... $users = Get-AzADGroupMember -GroupDisplayName 'readonlygroup'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-AzADGroupMember], Exception
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ActiveDirectory.GetAzureADGroupMemberCommand
Script stack trace:
at <ScriptBlock>, D:\home\site\wwwroot\{functionname}\run.ps1: line 110
System.Exception: Insufficient privileges to complete the operation.
I'm assuming its because the identity associated with the Function app doesn't have appropriate access to Azure Active directory. I was able to assign role assignments to the app identity to manage subscriptions but I don't see any options on how to setup a similar configuration to access AD from function app.
How can I run this command from my azure powershell function?

Try going to your azure ad, roles and administrators, choose a role that allows you to perform the ps functions you want, in this case you are trying to read groups, so maybe directory readers then click add assignments. find your function name, or from the function app identity blade, copy the object id shown, then paste it in the add assignments searchbox, it should find it, add it there.. may take up to 24 hrs to take effect but usually much quicker, then you should be able to run those ps commands.
the azure role assignments you added from the identity blade in the function only gives it for example subscription access, not access to azure ad.

Related

Unable to assign a role to user assigned identity through Azure Run books

By using the below command, trying to assign a role to the managed identity using PowerShell runbook(5.1 Runtime version).
$roleAssignment = New-AzRoleAssignment -ObjectId 'xxxx-xxxx-xxxx-xxxx' -Scope '/subscriptions/xxxx-xxxx-xxxx/resourceGroups/xxxxxxxxx' -RoleDefinitionName 'Contributor'
When we execute the runbook we ran into the below error.
Exception of type 'Microsoft.Rest.Azure.CloudException' was thrown.
But, When executed the same command from local PowerShell ISE we are able to assign the role with out any fail.
How to make runbook to assign the role to the user assigned identity.
Can any one help me solve this.
Unable to assign a role to user assigned identity through Azure Run books (1).html
Unable to assign a role to user assigned identity through Azure Run books
Exception of type ‘Microsoft.Rest.Azure.CloudException’ was thrown.
To resolve the above error, I would suggest you try to follow the below workaround that worked for me: -
Go to Azure AD --> App registrations --> Select your app --> API Permissions --> Add permission --> Microsoft Graph (You can select any Azure resource for which you want to grant permissions for) --> Application Permissions --> Directory --> Directory.Read.All
Then grant admin consent for the selected permissions for that particular resource.
Here, you can select other services which you are using, also in ‘Request API Permissions’ other than Microsoft Graph, you can use other APIs that you are working since the process is same as shown in the below snapshot: -

How to reset credentials of an Azure service principal using an automation account PowerShell runbook?

I'm trying to reset the password credentials of a service principal (let's call it SP1) through the following PowerShell commands:
Remove-AzADSpCredential -ObjectId <SP1_objectId> -Force
$Password = New-AzADSpCredential -ObjectId <SP1_objectId>
This works well when I run it through the PowerShell by my own user account, which has an Owner role assigned to SP1.
I also have this code in a runbook in an automation account with a "run as account" service principal (let's call it SP2).
I assigned the ownership of SP1 to SP2 as well through the command Add-AzureADServicePrincipalOwner and confirmed it through Get-AzureADServicePrincipalOwner.
I expected the runbook to be able to run the Remove-AzADSpCredential command on the SP1 after making its service principal the owner of SP1. But I get the following error:
Remove-AzADSpCredential : Insufficient privileges to complete the operation. At line:43 char:9 + Remove-AzADSpCredential -ObjectId $key.Name -Force + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Remove-AzADSpCredential], Exception + FullyQualifiedErrorId : Microsoft.Azure.Commands.ActiveDirectory.RemoveAzureADSpCredentialCommand
And the same error for New-AzADSpCredential command as well.
I thought maybe the ownership of SP1 should be assigned to the App for the run as account, instead of its service principal.
So I also ran the following:
Add-AzureADServicePrincipalOwner -ObjectId <SP1_ObjectId> -RefObjectId <runasaccount_app_ObjectId>
But this wasn't possible, as I got the error:
Code: Request_BadRequest
Message: The reference target 'Application_xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx' of type 'Application' is invalid for the 'owners' reference.
So I assume the ownership should have been assigned only to SP2, and not to the app.
I looked at here but the accepted answer says
If your user accounts are the Owner of the service principal(Enterprise application), the command New-AzADSpCredential will work.
which is true in my case, and yet, it's not working when running the runbook.
I also looked at here and it seems I need to do the #1 which the OP describes as easy to do.
Any input on how to do this will be greatly appreciated.
If you want to use a service principal to add/remove credentials for another service principal, it is different from using a user account to do that.
I assigned the ownership of SP1 to SP2 as well through the command Add-AzureADServicePrincipalOwner and confirmed it through Get-AzureADServicePrincipalOwner.
This way is correct, but not only the Owner, also you need to give an Application.ReadWrite.OwnedBy Application permission in Azure Active Directory Graph (Not Microsoft Graph)API after that.
Navigate to the API permissions of your automation account corresponded AD App in the portal -> add the permission like below, don't forget to click the Grant admin consent for xxx button at last.
Then test it in the runbook, it works fine.
New-AzADSpCredential -ObjectId xxxxxxxxxxxxx
The combination of Owner and Application.ReadWrite.OwnedBy is the minimum privilege in this case, there are also other ways, you can also give the Application Administrator directory role as you saw here or Application.ReadWrite.All Application permission in Azure Active Directory Graph, both will work.

PnP Powershell Add-PnPOffice365GroupToSite Authorization_RequestDenied Azure Runbook

We are using an Azure Runbook with PnP PowerShell to automate provisioning of SharePoint Online and O365 groups.
To connect and authenticate through PnP PowerShell, we are using an AppId and AppSecret that have assigned to an Azure Run As account.
Connecting to PnP Powershell through the Connect-PnPOnline command passing in the AppId and AppSecret works nicely.
We are then able to create a new site using New-PnPTenantSite, however when we go to create a group using Add-PnPOffice365GroupToSite we get the following error.
{"odata.error":{"code":"Authorization_RequestDenied","message":{"lang":"en","value":"Insufficient privileges to
complete the operation."},"requestId":"fd2a5b37-98ea-40ab-bf39-5db8fafe9057","date":"2020-02-05T13:04:08"}}
At line:75 char:1
+ Add-PnPOffice365GroupToSite -Url "$siteFullUrl" -Alias "$MailboxName" ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (:) [Add-PnPOffice365GroupToSite], ServerException
+ FullyQualifiedErrorId : EXCEPTION,SharePointPnP.PowerShell.Commands.Admin.AddOffice365GroupToSite
We have granted SharePoint tenant management privileges through the /_layouts/AppInv.aspx page, and also provided API access directly to the AppRegistration in Azure. We have assigned most permissions that relate to Groups, Sites and AD, however continue to receive the error above.
Does anyone have any info on what API permissions we need to assign to this app registration to allow it to create the office 365 group using this method?
The above screenshot shows the API permissions assigned to the app registration.
It turns out that certain operations require user interaction for auditing purposes - group creation being one of them.
Reference here with an answer from Andrew Connell -> https://github.com/SharePoint/sp-dev-docs/issues/3799

Add AAD application as a member of a security group

I'm trying to enable service to service auth using AAD tokens. My plan is to validate "groups" claim in the token to make sure the caller is a member of a security group that we created.
For example, we will create group1 for readers and group2 for writers. Then based on "groups" claim, I will figure out the right access level.
I use AAD app to issue the tokens (not a user), so I need that app to be a member of the security group. Azure AD powershell doesn't seem to accept application ids as group members. How to solve this? are there any other recommended patterns when the caller is another AAD app?
Command used:
https://learn.microsoft.com/en-us/powershell/module/azuread/Add-AzureADGroupMember?view=azureadps-2.0
Error:
Add-AzureADGroupMember : Error occurred while executing AddGroupMember
Code: Request_BadRequest
Message: An invalid operation was included in the following modified references: 'members'.
RequestId: 0441a156-3a34-484b-83d7-a7863d14654e
DateTimeStamp: Mon, 11 Dec 2017 21:50:41 GMT
HttpStatusCode: BadRequest
HttpStatusDescription: Bad Request
HttpResponseStatus: Completed
At line:1 char:1
+ Add-AzureADGroupMember -ObjectId "9c2cdf89-b8d6-4fb9-9116-7749adec85c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Add-AzureADGroupMember], ApiException
+ FullyQualifiedErrorId : Microsoft.Open.AzureAD16.Client.ApiException,Microsoft.Open.AzureAD16.PowerShell.AddGroupMember
Unfortunately, you cannot add an application as a member of Azure AD group.
Though the official document for the Powershell cmdlet Add-AzureADGroupMember doesn't make clear you cannot use Application's ObjectId as the RefObjectId, absolutely you cannot use it.
You cannot add an application as a member of Azure AD group neither.
For example, we will create group1 for readers and group2 for writers.
Then based on "groups" claim, I will figure out the right access
level.
For your scenario, I'm afraid that you couldn't achieve this for now. I understand why you need this. According to your request, my thought is assigning your application from Enterprise Application to Groups or users and manger users with different access rights. However, you cannot choose more roles for the selected group. The only one role is default access If want to define more roles for the app, you can refer to this documentation.
I also tried to use Azure AD RBAC and create new conditional access for my test app,but all don't have read only this choice.
You can also put your idea in Azure Feedback Forum, azure team will see it. Also, I will upvote your idea.
Update:
Currently, you can add a service principal to an AAD Group:
Example:
$spn = Get-AzureADServicePrincipal -SearchString "yourSpName"
$group = Get-AzureADGroup -SearchString "yourGroupName"
Add-AzureADGroupMember -ObjectId $($group.ObjectId) -RefObjectId $($spn.ObjectId)
Updated 2:
Recently, I also see lots of users want to assign roles to a service principal to let the service principal have some permissions to access to the app with a role.
I want to make clear here. Role-based authorized should be used for users, NOT applications. And it's not designed for applications. If you want to give some different permissions you may consider to assign application permissions to your service principal instead.
You can expose your Web App/API with application permissions by editing the Manifest in app registrations.
You can go to Azure portal > Azure Active Directory > App registrations > Select your App > Manifest.
In appRoles, you can insert content like this:
{
"allowedMemberTypes": [
"Application"
],
"displayName": "Access to the settings data",
"id": "c20e145e-5459-4a6c-a074-b942bbd4cfe1",
"isEnabled": true,
"description": "Administrators can access to the settings data in their tenant",
"value": "Settingsdata.ReadWrite.All"
},
Then, you can go another app registration you want to give permission > Settings > require permissions > Add > Search the application name you want to access > Choose the application permission you created before.
Therefore, your sp can obtain a token with that application permissions in token claims.
Also, for authorization from the resource, you need to add code logic to give control policy for that token with Settingsdata.ReadWrite.All claim.
Update 3
Currently, you can add the service principal to one AAD Group directly in Azure portal:
Following Update 3 in the answer of #Wayne Yang, I've successfully implemented this using C# and the MS Graph SDK.
But I think the same should be possible using Powershell and simple REST API calls.
// create new application registration
var app = new Application
{
DisplayName = principal.DisplayName,
Description = principal.Description,
};
app = await _graphClient.Applications.Request().AddAsync(app);
// create new service Principal based on newly created application
var servicePrincipal = new ServicePrincipal
{
AppId = app.AppId
};
// add service principal
servicePrincipal = await _graphClient.ServicePrincipals.Request().AddAsync(servicePrincipal);
// add service principal to existing security group
await _graphClient.Groups[groupId].Members.References.Request().AddAsync(servicePrincipal);

How does a service administrator get enough permission to create azure custom roles

I'm trying to create a Custom Role in azure (RBAC). But when I execute the powershell command New-AzureRmRoleDefinition here is the message I get saying that I'm not authorized to create it.
> New-AzureRmRoleDefinition .\developer_access_rbac.json
New-AzureRmRoleDefinition : AuthorizationFailed: The client 'admin#company.com' with object id
'{guid}' does not have authorization to perform action
'Microsoft.Authorization/roleDefinitions/write' over scope
'/providers/Microsoft.Authorization/roleDefinitions/{guid}'.
At line:1 char:1
+ New-AzureRmRoleDefinition .\developer_access_rbac.json
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureRmRoleDefinition], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Resources.NewAzureRoleDefinitionCommand
I asked from one of our administrators in our organization and he says the account admin#company.com is already a Global Administrator. And in the active directory admin#company.com is displayed as a Service Administrator.
I'm a little confused by these permission levels in azure. Can anyone explain to me how to acquire the needed permission to the account admin#company.com for solving the issue.
Taken from https://azure.microsoft.com/en-us/documentation/articles/role-based-access-control-custom-roles/#custom-roles-access-control:
Who can create a custom role? Owners (and User Access Administrators) of subscriptions, resource groups, and resources can create custom roles for use in those scopes. The user creating the role needs to be able to perform Microsoft.Authorization/roleDefinition/write operation on all the AssignableScopes of the role.
Who can modify a custom role? Owners (and User Access Administrators) of subscriptions, resource groups, and resources can modify custom roles in those scopes. Users need to be able to perform the Microsoft.Authorization/roleDefinition/write operation on all the AssignableScopes of a custom role.
Who can view custom roles? All built-in roles in Azure RBAC allow viewing of roles that are available for assignment. Users who can perform the Microsoft.Authorization/roleDefinition/read operation at a scope can view the RBAC roles that are available for assignment at that scope.
I actually came across this same issue and found the error to be misleading.
I had to clear the assignable scopes and then add one back.
$role.AssignableScopes.Clear()
$role.AssignableScopes.Add("/subscriptions/12345678912345789123456789")
I encountered the same kind of issue. The problem was with the AssignableScopes section in the json file. Just needed to add: /subscriptions/

Resources