kevin
kevin

Reputation: 491

Service Principals I create are not being created as mine

I've executed the code below to create a service principal and then list all of my service principals. However, the service principal I just created is not listed.

Code creating SP and listing all of mine SPs

Upvotes: 0

Views: 128

Answers (1)

Sridevi
Sridevi

Reputation: 22352

When I ran those CLI commands in my environment, I too got same response like this:

 az ad sp create-for-rbac
 az ad sp list --show-mine 

Response:

enter image description here

This happens if the signed-in user has Admin roles like Global Administrator of the tenant, that won't be added as Owner of newly created service principal which can be checked here in Enterprise applications:

enter image description here

But when I ran the same commands by signing in with new user account not having Global Administrator access, got response successfully like this:

 az ad sp create-for-rbac
 az ad sp list --show-mine 

Response:

enter image description here

In such cases where you are logging with Admin accounts, you can make use of below bash script that adds signed-in user as Owner of newly created service principal explicitly:

sp_create=$(az ad sp create-for-rbac)
echo "Output of 'az ad sp create-for-rbac':"
echo "$sp_create"

appId=$(echo $sp_create | jq -r '.appId')

# Retrieve the objectId of the service principal
spObjectId=$(az ad sp show --id $appId --query id --output tsv)
echo "Service Principal Object ID: $spObjectId"

# Get the objectId for the signed-in user
ownerObjectId=$(az ad signed-in-user show --query id -o tsv)
echo "Owner Object ID: $ownerObjectId"

# Add the signed-in user as an owner to the service principal
add_owner_response=$(az rest -m POST -u https://graph.microsoft.com/beta/servicePrincipals/$spObjectId/owners/\$ref -b "{\"@odata.id\": \"https://graph.microsoft.com/beta/directoryObjects/$ownerObjectId\"}")
echo "Owner added successfully to the service principal."

Response:

enter image description here

To confirm that, I checked the same in Portal where signed-in user is added as Owner of service principal like this:

enter image description here

When I ran the same command now to list applications owned by signed-in user having Admin access, I got response with expected results:

 az ad sp list --show-mine 

Response:

enter image description here

Reference: Overview of enterprise application ownership - Microsoft Entra ID

Upvotes: 2

Related Questions