Add AAD application as a member of a security group - azure

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

Related

The client 'XXX' with object id 'XXX' does not have authorization to perform action 'Microsoft.Media/mediaServices/transforms/write'

I am trying to use the following git repo in order to connect to azure ams, upload a video and stream it:
https://github.com/Azure-Samples/media-services-v3-node-tutorials/blob/main/AMSv3Samples/StreamFilesSample/index.ts
For some reason I am keep getting the following error:
The client 'XXX' with object id 'XXX' does not have authorization to perform action 'Microsoft.Media/mediaServices/transforms/write' over scope '/subscriptions/XXX/resourceGroups/TEST-APP/providers/Microsoft.Media/mediaServices/TESTAMP/transforms/ContentAwareEncoding' or the scope is invalid. If access was recently granted, please refresh your credentials
The AD user is owner but I understand it is a permission issue.
I searched all over the web for hours what permission do I need to grant and where but could not find any solution
The error get thrown here:
let encodingTransform = await mediaServicesClient.transforms.createOrUpdate(resourceGroup, accountName, encodingTransformName, {
name: encodingTransformName,
outputs: [
{
preset: adaptiveStreamingTransform
}
]
});
of course, I have updated the .env file to the correct data of my azure account.
Can anyone point out what am I missing and how to grant this permission?
Thanks!
The error message is referring to your Service Principal that is being used to authenticate against the AMS SDK.
Double check that you entered the GUID values for the service principal ID and Key, and make sure you did not use the friendly name in there.
AADCLIENTID="00000000-0000-0000-0000-000000000000"
AADSECRET="00000000-0000-0000-0000-000000000000"
Also, double check in IAM Access control in the portal that the service principal exists under the Role Assignments for your Media Services account and has Contributor or Owner permission Role first.
If you are in an Enterprise that locks down AAD access - you may need to work with your AAD owner/admin to make these changes and grant the service principal the right roles for your account. That's a bit outside of Media Services, and is just general Azure AAD application creation rights, and role assignments.
If you are still hitting issues, I would file a support ticket and also ask your AAD administrator to assign the role permisssion to your service principal.
As an aside, we are also working on updated Node.js SDK samples for the upcoming (soon!) release of the 10.0.0 Javascript SDK.
See the beta samples here - https://github.com/Azure-Samples/media-services-v3-node-tutorials/tree/10.0.0-beta.1

Azure : Permission for Service Principal to get list of Service Principals

I am using the Fluent Azure SDK for .NET to try fetching the list of all service principals in the tenant.
var authenticatedContext = Azure.Authenticate(
await SdkContext.AzureCredentialsFactory.FromServicePrincipal(aadClientId, aadClientSecret, tenantId, "AzureGlobalCloud")
);
var sps = authenticatedContext.ServicePrincipals.ListAsync().GetAwaiter().GetResults();
The service principal with the AAD Client Id has Directory.Read.All API permission.
(Just to be sure I'm not missing anything : I see this permission in ServicePrincipal -> Permissions section in the Azure Portal)
But still, the following error is thrown :
Microsoft.Azure.Management.Graph.RBAC.Fluent.Models.GraphErrorException: Operation return an invalid status code 'Forbidden'
However, the callouts to get ADGroup and list of subscriptions work
var subs = authenticatedContext.Subscriptions.ListAsync().GetAwaiter().GetResults();
var sgs = authenticatedContext.Subscriptions.ActiveDirectoryGroups().GetByIdAsync(someId).GetAwaiter().GetResults();
I don't know what permissions are missing.
I test the code in my side, and use fiddler to catch the request. It seems the sdk request Azure AD graph api but not Microsoft graph api to list the service principals. So you need to add permission Directory.Read.All of AAD graph but not Microsoft graph. Please refer to the steps below:
After adding the permission, do not forget grant admin consent for it. Then you can run your code success to get the service principal.
By the way, there is a bug with AAD permission Directory.Read.All. If we add AAD permission Directory.Read.All into the registered app, then the permission can not be removed even if we remove it from the page. So you still can run the code success even if you remove the Directory.Read.All from "API permissions" tab on the page.

Grant O365 Mailbox Permission to a Managed Identity

Trying to get an Logic App to get email message details via Graph API because the O365 Outlook Connector does not provide the output I need but Graph API does (Internet message headers).
The Outlook connector creates an API Connection for authentication and that works great.
To call Graph API I am using the HTTP action and it supports Managed Identity, so I'm wondering:
Can I grant permission such that the Managed Identity can read a certain mailbox?
Can the HTTP action use an API Connection (similar to what the Outlook connector does)?
1.Can I grant permission such that the Managed Identity can read a certain mailbox?
The managed identity is a service principal, which we can check it and its permissions in the Azure portal -> Azure Active Directory -> Enterprise applications. But we could not add new permissions in that, so we need to create a new AD App in the App registrations, add credentials to your app
, then grant the Mail.Read application permission of Microsoft Graph API, refer to this link. The permission is to call this api List messages(I suppose you want to use this api, if not, just follow the doc to find the application permission, add it.) At last, don't forget to click the Grant admin consent button.
In the logic app, use Active Directory OAuth for Authentication, https://graph.microsoft.com/ for Audience, and specific the URL, Client id, secret, etc, what need to call the MS graph api. xxx#microsoft.com is the user principal name, also is the mailbox address. I am not sure I understand the read a certain mailbox in your question correctly enough, if you mean you want to grant the permission just for only one mailbox, I will say there is no such permission in Microsft graph.
2.Can the HTTP action use an API Connection (similar to what the Outlook connector does)?
There is no pre-bulit connector for http action, you could try the Custom connectors in Logic Apps.
There is a way to add that application role permission to the Managed Identity. It is not possible to do that using the Azure Portal. You can verify in the Azure Portal that the steps below worked though. This method saves you creating a principal yourself and removes the need for client id/secret bookkeeping.
When you use Powershell, it is possible to add the Mail.Read application role permission to a managed identity, be it a system managed or user managed identity. There are other ways of performing the same steps, e.g. Azure CLI. But below is what I know works and have used.
The steps are usable for any identity and application with assignable app roles. So you can also add Sharepoint permissions to list sites, open an Excel sheet. But keep in mind that the Microsoft app roles are mostly all or nothing. It breaks the principle of least priviliged permissions.
I would love to know a generic way to avoid breaking the principle.
To assign an app role permission to a managed identity we need to know a couple of things:
the id of...
...the managed identity (e.g. "logic-app-identity")
...the application that has the application role (e.g. "Microsoft Graph")
...the id of the application role to assign to the managed identity (e.g. "Mail.Read")
And then we can assign the app role to the managed identity.
Set up some variables for readability
$managed_identity_name = "logic-app-identity"
$application_with_the_required_role_name = "Microsoft Graph"
$application_role_to_assign_name = "Mail.Read"
Use AzureAD module and login.
Use the AzureAd module from here
Import-Module AzureAd
Connect-AzureAd #shows popup to login
1. Get the managed identity id
# filter first server side, and in case of multiple results, the where ensures a single result
# -All is necessary because a managed identity is a sort of service principal
$managed_identity_id = (Get-AzureADServicePrincipal -All $true -SearchString $managed_identity_name | where DisplayName -eq $managed_identity_name).ObjectId
2. Get the application with the requested application roles
# -SearchString on "Microsoft Graph" returns two results, therefore the where clause to ensure a single result
# storing the returned object, because it contains the approles array
$application_with_the_required_role = (Get-AzureADServicePrincipal -SearchString "Microsoft Graph" | where DisplayName -eq "Microsoft Graph")
# fun fact: the ObjectId of the "Microsoft Graph" application is always: 94d0e336-e38a-4bfc-9b21-8fbb74b6b835
$application_with_the_required_role_id = $application_with_the_required_role.ObjectId
3. Get the application role id to assign to the managed identity
# the required id is now simply called Id
# fun fact: the ObjectId of the "Mail.Read" app role is always: 810c84a8-4a9e-49e6-bf7d-12d183f40d01
$application_role_to_assign_id = ($application_with_the_required_role.AppRoles | where Value -eq $application_role_to_assign_name).Id
Assign the app role to the managed identity
New-AzureADServiceAppRoleAssignment -ObjectId $managed_identity_id -PrincipalId $managed_identity_id -ResourceId $application_with_the_required_role_id -Id $application_role_to_assign_id
BONUS: verify-ish the assignment
# should list the assigned application to the identity, dig further for the specific app role
# (I don't know how :S)
Get-AzureADServiceAppRoleAssignedTo -ObjectId $managed_identity_id | fl
# and the other way around to list the identities assigned to the application
Get-AzureADServiceAppRoleAssignment -ObjectId $application_with_the_required_role_id | fl

Grant an existing B2C app access to graph API

I have an existing B2C app that I want to give graph access to.
I set this up previously but now want to replicate it but everything i can find is for new apps. I ysed the older graph but i think the article I used has been moved as everything is talking about the new Graph api
Is there a specific article for this, also if anyone has seen an article that describes the process from moving from Azure graph to Microsoft Graph (the new version) for a B2C app that would be great
Thanks
Register the application for the Graph API
In addition to registering the application in the B2C directory,
we must also create an application registration for the graph API.
The three key/id values you will need are the tenantId, ObjectId,
and AppPrincipalId.
To get the tenantId, log into the azure ad b2c directory in the new portal.
https://portal.azure.com/
Be sure you have the correct directory selected after you login
(top right corner).
Click on the help button (a question mark inside a circle) near the
top right corner of the page. In the menu that appears, click the
"Show diagnostics" option. This will display a JSON formatted output in
a new popup/window. Look for the "tenants" array and find the entry
with the display name of the directory you wish to register with the
application. The "id" attribute of that entry is the tenantId.
Example:
{
"clientSessionStartDate": {
//stuff will be here ...
},
//
// more shtuff you don't care about will be here ...
//
"tenants": [
{
"id": "SomeUUIDwithlike36charactersSometime",
"domainName": "yourtenantname.onmicrosoft.com",
"displayName": "displanynameoftenant",
"isSignedInTenant": true
},
// ... snippity lemon
]
// ... snip some more
}
You will also need a unique application Secret and AppPrincipalId to be
generated for the new application.
Also, to set the correct permissions for the application, you will need
its "ObjectId".
The process for registering the application and generating those values
is more complicated, and requires a special module for PowerShell
and the online login module to be downloaded and installed.
Also, be sure you have the latest version of PowerShell installed for
your system, or you will not be able to use the azure module.
Sign-In assistant: https://www.microsoft.com/en-us/download/details.aspx?id=41950
Azure AD PowerShell Module: http://go.microsoft.com/fwlink/p/?linkid=236297
Create the application registration with PowerShell
This next section is an almost verbatim copy-paste fo the documentation.
https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/
After you install the PowerShell module, open PowerShell and connect to
your B2C tenant.
> $msolcred = Get-Credential
After you run Get-Credential, you will be prompted for
a user name and password, Enter the user name and password
of your B2C tenant administrator account.
> Connect-MsolService -credential $msolcred
Before you create your application, you need to generate a new client
secret. Your application will use the client secret to authenticate to
Azure AD and to acquire access tokens. You can generate a valid secret
in PowerShell:
> $bytes = New-Object Byte[] 32
> $rand = [System.Security.Cryptography.RandomNumberGenerator]::Create()
> $rand.GetBytes($bytes)
> $rand.Dispose()
> $newClientSecret = [System.Convert]::ToBase64String($bytes)
> $newClientSecret
The final command should print your new client secret. Copy it somewhere safe. You'll need it later. Now you can create your application by providing the new client secret as a credential for the app:
> New-MsolServicePrincipal -DisplayName "My New B2C Graph API App" -Type password -Value $newClientSecret
Example output:
DisplayName : My New B2C Graph API App
ServicePrincipalNames : {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
ObjectId : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
AppPrincipalId : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
TrustedForDelegation : False
AccountEnabled : True
Addresses : {}
KeyType : Password
KeyId : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
StartDate : 1/1/2017 1:33:09 AM
EndDate : 1/1/2017 1:33:09 AM
Usage : Verify
If you successfully create the application, it should print out
properties of the application like the ones above, but with a mix of alpha-numeric characters. You'll need both
ObjectId and AppPrincipalId, so copy those values, too.
You will also need the tenant ID of the B2C directory.
After you create an application in your B2C tenant, you need to assign
it the permissions it needs to perform user CRUD operations. Assign the
application three roles: directory readers (to read users), directory
writers (to create and update users), and a user account administrator
(to delete users). These roles have well-known identifiers, so you can
replace the -RoleMemberObjectId parameter with ObjectId from above and
run the following commands. To see the list of all directory roles,
try running Get-MsolRole.
> Add-MsolRoleMember -RoleObjectId 88d8e3e3-8f55-4a1e-953a-9b9898b8876b -RoleMemberObjectId <Your-ObjectId> -RoleMemberType servicePrincipal
> Add-MsolRoleMember -RoleObjectId 9360feb5-f418-4baa-8175-e2a00bac4301 -RoleMemberObjectId <Your-ObjectId> -RoleMemberType servicePrincipal
> Add-MsolRoleMember -RoleObjectId fe930be7-5e62-47db-91af-98c3a49a38b1 -RoleMemberObjectId <Your-ObjectId> -RoleMemberType servicePrincipal
You now have an application that has permission to create, read,
update, and delete users from your B2C tenant.
I totally forgot this great answer exists and this is how you do it
Authorize By Group in Azure Active Directory B2C

New-AzureRmRoleAssignment programmatically in a .NET Core console application

It seems I'm on a journey to first programmatically create an Azure application and then use Azure Management APIs to do create some resource. There's a new snag I'd like to ask from the community, how to do basically the PowerShell command New-AzureRmRoleAssignment -RoleDefinitionName Owner -ServicePrincipalName $adApp.ApplicationId.Guid using HttpClient (or some smarter method with the exact needed permissions using Microsoft Graph API libraries).
Trying to be a better person this time (being more around, providing code), I prepared a repo in GH, but the issue basically boils down to what kind of a URI should be used (here). The code is
var roleAssignment = $"{{something here}}";
var roleAssignementContent = new StringContent(roleAssignment, Encoding.UTF8, "application/json");
var roleAssignmentResponse = await client.PostAsync($"https://graph.windows.net/{tenants.value[0].tenantId}/applications/{createdApplication.appId}?api-version=1.6", roleAssignementContent).ConfigureAwait(false);
var roleAssignement = await roleAssignmentResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
I fiddled with Graph API Explorer too if things were easier using it (or the libraries) but with less luck. Indeed, the ultimate goal is to create application programmatically so that it becomes possible to use Azure Management Libraries to make a deployment. That is, all in code from the beginning to an end.
(Also, the code is of throwaway quality, to provide a more functioning example only.)
New-AzureRmRoleAssignment is used to assign the specified RBAC role to the specified service principal , you could achieve that by using the Resource Manager create role assignment API:
Get ObjectId of application service principal.
if you have got the objectId of application service principal before , you could skip this step .If not , you could use Azure ad graph api to request an application's service principal by application id :
GET https://graph.windows.net/<TenantID>/servicePrincipals?$filter=servicePrincipalNames/any(c:%20c%20eq%20'applicationID')&api-version=1.6
Authorization: Bearer eyJ0eXAiOiJK*****-kKorR-pg
Get Azure RBAC role identifier
To assign the appropriate RBAC role to your service principal, you must know the identifier of the Azure RBAC role(Owner in your scenario), you could call the Resource Manager role definition API to list all Azure RBAC roles and search then iterate over the result to find the desired role definition by name.:
GET https://management.azure.com/subscriptions/ed0caab7-c6d4-45e9-9289-c7e5997c9241/providers/Microsoft.Authorization/roleDefinitions?$filter=roleName%20eq%20'Owner'&api-version=2015-07-01
Authorization: Bearer
Assign the appropriate RBAC role to service principal:
PUT https://management.azure.com/subscriptions/ed0caab7-c6d4-45e9-9289-c7e5997c9241/providers/Microsoft.Authorization/roleAssignments/16fca587-013e-45f2-a03c-cfc9899a6ced?api-version=2015-07-01
Authorization: Bearer eyJ0eXAiOiJKV1QiL*****FlwO1mM7Cw6JWtfY2lGc5
Content-Type: application/json
{
"properties": {
"roleDefinitionId": "/subscriptions/XXXXXXXXXXXXXXX/providers/Microsoft.Authorization/roleDefinitions/XXXXXXXXXXXXXXXXX",
"principalId": "XXXXXXXXXXXXXXXXXXXXX"
}
}
roleDefinitionId is the id you get in step 2 ,principalId is the objectId you get in step 1 . ed0caab7-c6d4-45e9-9289-c7e5997c9241 is the subscription id ,16fca587-013e-45f2-a03c-cfc9899a6ced is a new guid created for the new role assignment .
Please refer to below document for more details :
Use Resource Manager authentication API to access subscriptions

Resources