Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authentication via Application-Permission #52

Open
aexlz opened this issue Aug 21, 2023 · 8 comments
Open

Authentication via Application-Permission #52

aexlz opened this issue Aug 21, 2023 · 8 comments

Comments

@aexlz
Copy link

aexlz commented Aug 21, 2023

Hello Everyone
I set up the pipeline with a Service-Principal, for which all the relevant API-Permissions have been consented.

Additionally I use Connect-MgGraph -TenantId $tenantId -ClientSecretCredential $clientSecretCredential to be able to authenticate properly with clientid and clientsecret.
I made sure that the app has the sufficient privileges by running Get-MgContext | Select-Object -ExpandProperty Scopes

After that I run Export-Entra $path -All, but receive the following output

Starting backup...
 Organization/Organization.json
 Organization/Settings.json
Response status code does not indicate success: Forbidden (Forbidden)

Long story short:
Is it possible to use this script with application-based permissions?

@aexlz
Copy link
Author

aexlz commented Aug 21, 2023

By playing around with the type-parameter, I was possible to export a few entities.
So it seems that not every Type is supported by an Application-Based Permission.

I do like the idea of this script a lot. It would be great to have those enhancements in the feature or at least some kind of a table in the readme.md, which is illustrates something like this:

Type Permission
User Application & Delegated
ConditionalAccess Application & Delegated
... ....

An additional suggestion would be to give the user a better hint by proper error-handling. My pipeline just stopped with e.g.:

Response status code does not indicate success: InternalServerError (Internal Server Error).
Response status code does not indicate success: Forbidden (Forbidden).
Response status code does not indicate success: BadRequest (Bad Request).

@Outlawpete285
Copy link

Hello,
In case it helps you: I gave the enterprise application the "Global Reader" role and was then able to export all the elements.
Of course, that's far too many permissions, but only read and you can secure the company application accordingly. This works fine for my automated Backup.

Best Regards

@israem
Copy link

israem commented Sep 21, 2023

I've been using this module with application permissions and it works flawlessly.
Here is a screenshot of the needed permissions:
image

Here is a snippet to configure the permissions:

# Use application ObjectId rather than clientID
$applicationObjectId = '....'
$requiredPermissionsNames = @(
	'AccessReview.Read.All',
        'Agreement.Read.All',
        'APIConnectors.Read.All',
        'Application.Read.All',
        'Directory.Read.All',
        'EntitlementManagement.Read.All',
        'IdentityProvider.Read.All',
        'IdentityUserFlow.Read.All',
        'Organization.Read.All',
        'Policy.Read.All',
        'Policy.Read.PermissionGrant',
        'PrivilegedAccess.Read.AzureAD',
        'PrivilegedAccess.Read.AzureResources',
        'User.Read.All',
        'UserAuthenticationMethod.Read.All'
)
# get service principal app roles for MS Graph
$sps = Get-MgServicePrincipalByAppId  -AppId "00000003-0000-0000-c000-000000000000"

# Get list of permissions with the id
$requiredAppRoles = $sps.AppRoles  | where {$_.value -in $requiredPermissionsNames}

# update the registered application. 
Update-MgApplication -ApplicationId $applicationObjectId -RequiredResourceAccess (@{
	ResourceAppId = '00000003-0000-0000-c000-000000000000'
	resourceAccess = $requiredAppRoles | foreach {@{Id =$_.id; Type='Role'} }
})

@tld6764
Copy link

tld6764 commented Sep 21, 2023

@israem what version of powershell are you running this in?

@israem
Copy link

israem commented Sep 22, 2023

I ran the module in both PS7 (up tp 7.2.14) and PS5 successfully. I ran the snippet of code I shared in PS7 but there is no reason it wouldn't work in PS5 if you have all the modules installed.

@tld6764
Copy link

tld6764 commented Sep 22, 2023

I see. I've been messing with it all week. Finally figured out that it gives me errors (same as in original post on this issue) in 7.X, but works fine in 5.1.

@ztrhgf
Copy link

ztrhgf commented Sep 29, 2023

Seems like same issue I encountered too #57

@Ju5t4GuyinT3ch
Copy link

Ju5t4GuyinT3ch commented Oct 24, 2024

I'm trying to use a service principal as well to automate the export. It's not working for me this way. I did a lot of tinkering and found the script provided below to work with no errors. The script states that it's Connected via userprovidedaccesstoken access using the ClientID. After script is ran and completed nothing shows in the folder that was created for the backup. I have tried this with a folder that already exists as well and in different drives/ folders.

# Define variables
$backupPath = "C:\Backup\EntraBackup\$((Get-Date).ToString('yyyy-MM-dd'))"
$tenantID = 'Tenant ID'  # Replace with your actual Tenant ID
$clientID = 'Application (client) ID'  # Replace with your Application (client) ID
$clientSecret = 'Application (client) secret'  # Replace with your Application (client) secret

# Create backup folder
New-Item -ItemType Directory -Path "$backupPath"

# Scopes required for the backup operation (Microsoft Graph API)
$scopes = @('https://graph.microsoft.com/.default')

# Convert the client secret into a secure string and pass to the New-MsalClientApplication
$secureClientSecret = (ConvertTo-SecureString "$clientSecret" -AsPlainText -Force)

# Install the necessary modules if not already installed
Write-Host 'Installing required modules...'
Install-Module -Name MSAL.PS 
Install-Module -Name Microsoft.Graph.Authentication
Install-Module -Name EntraExporter

# Create the MSAL Confidential Client Application (Service Principal Authentication)
Write-Host 'Authenticating using Service Principal...'
$msalApp = New-MsalClientApplication -clientId $clientID -clientSecret $secureClientSecret -Authority "https://login.microsoftonline.com/$tenantID"

# Acquire the token for Microsoft Graph API
Write-Host 'Acquiring token for Microsoft Graph API...'
$tokenResponse = Get-MsalToken -clientID $clientID -clientSecret $secureClientSecret -tenantID $tenantID -Scopes $scopes

# Extract the access token from the response
$graphToken = (ConvertTo-SecureString $tokenResponse.AccessToken -AsPlainText -Force)

# Check if the token was retrieved successfully
if (-not $graphToken) {
    Write-Host "Failed to obtain access token. Exiting script."
    exit
}

Write-Host "Successfully authenticated. Access Token acquired."

# Connect to Microsoft Graph using the acquired token
Write-Host 'Connecting to Microsoft Graph...'
Connect-MgGraph -AccessToken $graphToken

# Connect to Entra ID and perform a full export
Write-Host 'Connecting to Entra ID...' 

# Start the backup process
Write-Host 'Starting backup...'
Export-Entra -Path "$backupPath" -All

Write-Host 'Backup complete...'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants