MSGraph – ALL

App registration vs Entreprise app

Différence App Registrations et Entreprise applications

L’enregistrement d’application permet d’enregistrer une application à intégrer avec Microsoft Entra ID (application que vous développez), tandis que les applications d’entreprise permettent l’enregistrement d’applications ainsi que l’ajout et la configuration d’applications SaaS à partir de la galerie d’applications Microsoft Entra. Les applications d’entreprise permettent également de publier les applications déployées sur site.

Les inscriptions d’applications sont l’endroit où vous enregistrez vos applications, tandis que les applications d’entreprise sont l’endroit où vous gérez l’accès à ces applications.

AppRegistration : app basées sur OIDC (OpenID Connect)
Enterprise App : app pouvant utilisées n’importe quelle norme.

En utilisant OpenID Connect ou SAML de façon indépendante, les entreprises peuvent assurer l’authentification des utilisateurs (user authentication) et déployer l’authentification unique (SSO). Bien que les deux permettent d’encadrer la connexion, ils présentent différents avantages et inconvénients.

OpenID Connect s’appuie sur le protocole OAuth 2.0, associé à un jeton JSON Web Token (JWT) supplémentaire, appelé « jeton d’identification » (ID token), pour normaliser les aspects pouvant être personnalisés avec OAuth 2.0, comme les étendues et la découverte des terminaux. Cette norme a été conçue spécifiquement pour l’authentification des utilisateurs. Elle est couramment utilisée pour permettre aux utilisateurs de se connecter à des applications mobiles ou à des sites web commerciaux.
SAML 2.0 est totalement indépendant d’OAuth et repose sur un échange de messages pour assurer une authentification au format SAML XML, plutôt que sur un jeton JWT. Cette norme est plus généralement utilisée pour permettre aux utilisateurs d’entreprise d’accéder à plusieurs applications en se connectant une seule fois.

Source :
https://www.okta.com/fr/identity-101/whats-the-difference-between-oauth-openid-connect-and-saml/
https://learn.microsoft.com/en-us/answers/questions/270680/app-registration-vs-enterprise-applications

Connexion via une APi

$ApplicationID = "x"
$TenantDomainName = "x"
$AccessSecret = "x"
$Body = @{    
Grant_Type    = "client_credentials"
Scope         = "https://graph.microsoft.com/.default"
client_Id     = $ApplicationID
Client_Secret = $AccessSecret
} 
$ConnectGraph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantDomainName/oauth2/v2.0/token" -Method POST -Body $Body
$token = $ConnectGraph.access_token

Vérification des rôles sur une application

$app = Get-AzureADApplication -ObjectId "$objectId"
$app.requiredResourceAccess | ConvertTo-Json -Depth 3

Affectation de permissions sur une identité managée

Affectation de permissions à une identité managé :
$TenantID=""
# Microsoft Graph App ID (DON'T CHANGE)
$GraphAppId = "00000003-0000-0000-c000-000000000000"
# Name of the manage identity (same as the Logic App name)
$DisplayNameOfMSI="" 
# Check the Microsoft Graph documentation for the permission you need for the operation
$PermissionName = "Mail.Send" 

# Install the module (You need admin on the machine)
#Install-Module AzureAD 

Connect-AzureAD -TenantId $TenantID -Credential $psCred
$MSI = (Get-AzureADServicePrincipal -Filter "displayName eq '$DisplayNameOfMSI'")
Start-Sleep -Seconds 10
$GraphServicePrincipal = Get-AzureADServicePrincipal -Filter "appId eq '$GraphAppId'"
$AppRole = $GraphServicePrincipal.AppRoles | `
Where-Object {$_.Value -eq $PermissionName -and $_.AllowedMemberTypes -contains "Application"}
New-AzureAdServiceAppRoleAssignment -ObjectId $MSI.ObjectId -PrincipalId $MSI.ObjectId `
-ResourceId $GraphServicePrincipal.ObjectId -Id $AppRole.Id

Send mail via Graph

$AppId = "xxx"  
$TenantId = "xxx"  
$AppSecret = 'xxx'  

$uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"  
$body = @{  
    client_id     = $AppId
    scope         = "https://graph.microsoft.com/.default"
    client_secret = $AppSecret
    grant_type    = "client_credentials" }  
  
$tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing  
$token = ($tokenRequest.Content | ConvertFrom-Json).access_token  
$headers = @{Authorization = "Bearer $token"}  

$accesstoken = ($token | ConvertTo-SecureString -AsPlainText -Force)
Connect-MgGraph -AccessToken $accesstoken -NoWelcome

$MailSenderUPN = "xxx@xxx.com"
$SendMailBody = @{
    Message = @{
        Subject = "Test"
        Body = @{
            ContentType = "HTML"
            Content =  "
                Test"`
        }
        ToRecipients = @(
            @{
                EmailAddress = @{
                    Address = 'yyy@xxx.com'
                }
            }
        )
    }
}
$SendMailUrl = "https://graph.microsoft.com/v1.0/users/$MailSenderUPN/SendMail"
Invoke-RestMethod -Uri $SendMailUrl -Headers @{Authorization = "Bearer $($token)"}  -Method Post -Body $($SendMailBody | convertto-json -depth 4) -ContentType "application/json; charset=utf-8"

Restrict send mail

Récupérer l'ID du groupe en question (doit être un mail enabled security group)
New-ApplicationAccessPolicy -AppId 'xxx' -PolicyScopeGroupId 'GroupID' -AccessRight RestrictAccess -Description "Restrict SendAs to members of this group"

Close sftp (storage acc) from automation

$resourceGroupName = "rg-xxx"
$storageAccountName = "stxxx"
$enableSftp = $True

#n vérifie de ne pas hérité d'un AzContext du RunBook
Disable-AzContextAutosave -Scope Process

Import-Module -Name Az.Storage
# Connexion à Azure via l'identité managée et définition du contexte
$AzureContext = (Connect-AzAccount -Identity).context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext


$SFTPStatusBefore = Get-AzStorageAccount -DefaultProfile $AzureContext -ResourceGroupName $resourceGroupName -Name $storageAccountName | Select-Object -ExpandProperty EnableSftp
Write-Output "Statut avant update : $SFTPStatusBefore"
#On change le statut en inversant la variable 
#$SFTPStatusBefore = $SFTPStatusBefore -replace 'True', 'Enabled' -replace 'False', 'Disabled'

if ($SFTPStatusBefore -match "True") {
    $SFTPStatusAfter = $SFTPStatusBefore -replace 'True', 'False'
    Write-Output "Passage en False - Before : $SFTPStatusBefore et after : $SFTPStatusAfter"
}
if ($SFTPStatusBefore -match "False") {
    $SFTPStatusAfter = $SFTPStatusBefore -replace 'False', 'True'
    Write-Output "Passage en True - Before : $SFTPStatusBefore et after : $SFTPStatusAfter"
}

$SetSFTP = [System.Convert]::ToBoolean($SFTPStatusAfter)

Set-AzStorageAccount -DefaultProfile $AzureContext -ResourceGroupName $resourceGroupName -Name $storageAccountName -EnableSftp $SetSFTP

$SFTPStatusAfter = Get-AzStorageAccount -DefaultProfile $AzureContext -ResourceGroupName $resourceGroupName -Name $storageAccountName | Select-Object -ExpandProperty EnableSftp
Write-Output "Statut après update : $SFTPStatusAfter"

Disable SFTP support on an Azure Storage account on a Schedule | luke.geek.nz

SUPPRESSION D’UNE LICENCE SUR UN GROUPE AZURE

La première étape consiste à se connecter en MS Graph API, voir cet article :

Ensuite, nous devons récupérer 2 attributs :
– Group ID (objectID)
– License ID (skuID)

Le groupID est récupérable via Get-MsolGroup en filtrant sur ObjectID. Vous pouvez lister tous les groupes via ces commandes

$apiUrl = 'https://graph.microsoft.com/v1.0/Groups/'
$Data = Invoke-RestMethod -Headers @{Authorization = "Bearer $($token)"} -Uri $apiUrl -Method Get
$Groups = ($Data | select-object Value).Value | Select-Object id,displayName
 
# Show the groups
$Groups

Ensuite, nous devons récupérer l’ID de licence identifié via skuID

$apiUrl = 'https://graph.microsoft.com/v1.0/Groups/<GUID>?$select=assignedLicenses'
$Data = Invoke-RestMethod -Headers @{Authorization = "Bearer $($token)"} -Uri $apiUrl -Method Get
$GroupData = $Data | select-object -ExpandProperty assignedLicenses
 
$GroupData | fl

Le retour de cette commande sera sous le format suivant :

Ensuite, nous allons utiliser ces informations pour retirer la licence du groupe.
Modifier les valeurs de $LicenseToRemove et $groupID afin que cela corresponde à ce que vous souhaitez updater.

$LicenceToRemove    = "c42b9cae-ea4f-4ab7-9717-81576235ccac"
$groupID            = "GROUP OBJECT ID"
 
$apiUrl             = "https://graph.microsoft.com/v1.0/Groups/$groupID/assignLicense"
 
##
 
# REMOVE License Body for RestAPI
$body = @{
    addLicenses = @()
    removeLicenses= @($LicenceToRemove)
}
 
# Convert it to JSON
$jsonBody = $body | ConvertTo-Json
 
$removeLicense = Invoke-RestMethod -Method Post -Headers @{
    Authorization = "Bearer $($token)"
    'Content-Type'  = "application/json"
} -Body $jsonBody -Uri $apiUrl
 
###
 
$removeLicense

Récupérer sous-sites

Récupérer l’ID dans Edm.Guid via
https://xxx.sharepoint.com/sites/xxx/_api/site/id

Puis sur graph explorer :
https://graph.microsoft.com/v1.0/sites/$Edm.Guid/sites

Récupérer personne sur un Shift

Exemple capitaine de production :
Me mettre Owner du Teams en premier, puis :

$params = @{
enabled = $true
timeZone = "Europe/Paris"
}
Set-MgTeamSchedule -TeamId "$dispodansadminteams" -BodyParameter $params
$date1 = $(get-date).adddays(-2).ToString("yyyy-MM-ddT00:00:00.000Z")
$date2 = $(get-date).ToString("yyyy-MM-ddT00:00:00.000Z")
$UserId = (Get-MgTeamScheduleShift -TeamId "$dispodansadminteams" -Filter "sharedShift/startDateTime ge 2025-03-05T00:00:00.000Z and sharedShift/endDateTime le 2025-03-07T00:00:00.000Z").UserId
$UserMail = (Get-MgUser -UserId $UserId).Mail
$UserMail