PnP Powershell Add-PnPOffice365GroupToSite Authorization_RequestDenied Azure Runbook - azure

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

Related

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.

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);

Azure AD B2C Insufficient privileges to complete the operation while using Graph API

I have started with https://github.com/AzureADQuickStarts/B2C-WebApp-OpenIdConnect-DotNet as the base
Created sign in profile in Azure B2C preview.
Sign in flows works wonderfully with MFA, used custom pages with the help of https://github.com/azureadquickstarts/b2c-azureblobstorage-client/.
CSS and styling works . However I realized that sign up form will be less onerous with Javascript autocomplete.
B2C dues to security issues had prohibited Javascript.
So I filled email/password with B2C flows and then decided to redirect it my own page within a mvc route of my original project. This one uses https://github.com/Azure-Samples/active-directory-dotnet-graphapi-web/blob/master/WebAppGraphAPI/Controllers/UsersController.cs as an inspiration for Graph API.
I am able to successfully get token via
adClient = new ActiveDirectoryClient( serviceRoot, async () => await GetAppTokenAsync());
However the following fails with "Insufficient privileges to complete" exception
userResult = (User)adClient.Users.GetByObjectId(userObjectID).ExecuteAsync().Result;
I have tried doing the following https://social.msdn.microsoft.com/Forums/azure/en-US/6dd08794-ab89-4513-91e5-546c97a85adc/graph-client-throwing-insufficient-privileges-to-complete-the-operation-on-creating-ad-user?forum=WindowsAzureAD as well as try https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console/issues/27 powershell trick
powershell fails with
C:\Users\Karan\Desktop\dev> $msolcred = Get-Credential cmdlet Get-Credential at command pipeline position 1 Supply values for the following parameters: Credential PS C:\Users\Karan\Desktop\dev> Connect-MsolService -credential $msolcred Connect-MsolService : Exception of type 'http://Microsoft.Online .Administration.Automation.MicrosoftOnlineException' was thrown. At line:1 char:1 + Connect-MsolService -credential $msolcred + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [Connect-MsolService], Mic rosoftOnlineException + FullyQualifiedErrorId : 0x800488D6,http://Microsoft.Online .Administration.Autom ation.ConnectMsolService .....
also tried steps mentioned in https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-graph-dotnet
Also added graph API permissions "Read / write directory" in B2C AD here
also ticked more options in Windows Azure Active Directory
As well as ticked then in Old portal.
This has been resolved. I had to create a new application. It was clearly written "Do not modify" against my B2C generated application - and I was modifying permissions for that. So I added a new application and granted that read and write directory. My mistake.

Adding a new Azure AD App Credential - What specific permissions or role memberships are needed?

I am trying to add a new password credential for my Azure AD Application, through the Powershell commandlet and I run into an insufficient permissions error.
New-AzureRmADAppCredential -ApplicationId "<my app guid>" -Password "<a new password>" -EndDate (Get-Date).Addyears(2)
Error Details
New-AzureRmADAppCredential : Insufficient privileges to complete the operation.
At line:1 char:1
+ New-AzureRmADAppCredential -ApplicationId "<some guid> ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-AzureRmADAppCredential], Exception
+ FullyQualifiedErrorId : Authorization_RequestDenied,Microsoft.Azure.Commands.ActiveDirectory.NewAzureADAppCredentialCommand
I have the same behavior when I try to add a new secret through the UI as well.
What are the specific permissions I am missing?
Please note this Azure AD is synced with an on-prem AD. I suspect the on-prem AD permissions are also coming into play here.
Any advice?
In order to update an application you must be a Tenant Administrator or marked explicitly as an owner of the application.
You can most easily check these things using the Graph Explorer.
You can check if you are a tenant administrator of the tenant using this Graph Query:
https://graph.windows.net/myorganization/me/memberOf
And then looking for the tenant administrator directory role to be listed.
And you can check if you are an owner of the application with this query:
https://graph.windows.net/myorganization/applications/{Object ID}/owners

Error - Connect-MsolService : Your credentials could not be authenticated. Try again

In Powershell, I executed the below cmdlets
Connect-MsolService
Getting error like below
Connect-MsolService : Your credentials could not be authenticated. Try again
or contact Technical Support.
At line:1 char:1
+ Connect-MsolService
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [Connect-MsolService], Mic
rosoftOnlineException
+ FullyQualifiedErrorId : 0x80048820,Microsoft.Online.Administration.Autom
ation.ConnectMsolService
I am giving the credentials of Azure portal account, what is wrong with this ? What credentials should I give ?
Tried below link:
https://msdn.microsoft.com/library/azure/jj151815.aspx#BKMK_connect --
I have latest version of MSOL libraries.
https://support.microsoft.com/en-in/kb/2412085 -- I am able open the azure management portal.
The below link says "Enter the user name and password of your B2C tenant administrator account."
https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/
I am using the username, that is co-administrator for the Azure Portal. Is it possible the co-administrator can connect to the MSOL Services.
Please suggest.
I had excatly the same problem. I solved it with creating a new Global Administrator as already mentioned.
Just wantend to state that:
-this must be done in the old portal, not the new one
-adding a native account to that AAD B2C, guest accounts do not work
The account you are using must be assigned the role of (Global) Administrator in Azure Active Directory as stated by the document you referenced:
Before you can create applications or users, or interact with Azure AD
at all, you will need an Azure AD B2C tenant and a global
administrator account in the tenant.
By default, all co-administrator accounts are added to Azure AD in 'Member' role.

Resources