Outils pour utilisateurs

Outils du site


reseau:cloud:azure:configurerapppoursharepoint

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
reseau:cloud:azure:configurerapppoursharepoint [2026/04/05 22:41] techer.charles_educ-valadon-limoges.frreseau:cloud:azure:configurerapppoursharepoint [2026/04/10 22:24] (Version actuelle) – [Utilisation d'un certificat] techer.charles_educ-valadon-limoges.fr
Ligne 7: Ligne 7:
   * depuis le **portail Azure**,   * depuis le **portail Azure**,
   * en **CLI/script** avec l'**API Microsoft Graph** par exemple en utilisant **Powershell**.   * en **CLI/script** avec l'**API Microsoft Graph** par exemple en utilisant **Powershell**.
-</WRAP>+
  
 ===== Installer le module Microsoft.Graph de Powershell===== ===== Installer le module Microsoft.Graph de Powershell=====
Ligne 14: Ligne 14:
 ==== Installer Microsoft.Graph de Powershell ==== ==== Installer Microsoft.Graph de Powershell ====
  
-    * prérequis : +  * prérequis : 
         * permissions API (Microsoft Graph) : Sites.Selected (Application)         * permissions API (Microsoft Graph) : Sites.Selected (Application)
  
-    * ouvrir une session Powershell en tant, qu'administrateur+  * ouvrir une session Powershell en tant, qu'administrateur
  
 <code> <code>
Ligne 100: Ligne 100:
   -KeyLength 2048 `   -KeyLength 2048 `
   -NotAfter (Get-Date).AddYears(4)   -NotAfter (Get-Date).AddYears(4)
- 
-$cert.Thumbprint 
- 
- 
- 
 </code> </code>
  
-  * Notez l'empreinte du certficat+  * Notez l'empreinte du certificat
  
 <code> <code>
Ligne 128: Ligne 123:
 $cert.HasPrivateKey doit renvoyer True $cert.HasPrivateKey doit renvoyer True
  
-   +=== Export du certificat PUBLIC (.cer) à importer dans Entra ID ===
- +
-  * Export du certificat PUBLIC à importer dans Entra ID+
  
 <code> <code>
Ligne 138: Ligne 131:
 </code> </code>
  
-    * importer le certificat dans l'application+  * importer le certificat dans l'application à partir du portail Azure 
 + 
 +  * Test avec PowerShell (certificat local)
  
 <code> <code>
-Add-MgApplicationKey  +Connect-MgGraph   
-     -ApplicationId $app.Id  ` +   -TenantId "<TENANT_ID>"  
-     -KeyCredentialFile "application.cer"+   -ClientId "<APP_ID>"   
 +   -CertificateThumbprint "<THUMBPRINT> 
 + 
 +=> Résultat attendu 
 +Plain TextWelcome To Microsoft Graph!
 </code> </code>
  
-=====================+  * Puis :
  
-  * script Powershell pour se conncter t etest la création d'un dossier +<code> 
 +Get-MgContext 
 + 
 +=> on doit voir : 
 + 
 +ClientId               : <id client> 
 +TenantId               : <ID tenant> 
 +Scopes                 : {Sites.Selected} 
 +AuthType               : AppOnly 
 +TokenCredentialType    : ClientCertificate 
 +CertificateThumbprint  : <empreinte> 
 +</code> 
 + 
 +=== Exporter le certificat pour obtenir un PFX PKCS#1 (clé privée incluse) ===
  
-<WRAP center round important> 
-Il est important de se connecter en tant qu'application et non en tant qu'utilisateur. 
-</WRAP> 
  
 <code> <code>
-############################################################ +$thumb = "EMPREINTE_DU_CERTIFICAT"
-# CONFIGURATION pour l'accès avec l'application enregistrée +
-############################################################+
  
-$TenantId     = "Tenant_educ-valadon# +$cert Get-Item "Cert:\CurrentUser\My\$thumb"
-$AppId        = "APP_ID_DE_TON_APPLICATION"+
  
-$Thumbprint = "EMPREINTE_DU_CERTIFICAT"+Export-PfxCertificate ` 
 +  -Cert $cert ` 
 +  -FilePath "graph-auth.pfx
 +  -Password (ConvertTo-SecureString -String "MotDePasseFort123!" -AsPlainText -Force) 
 +</code>
  
-$SitePath      "/sites/Signaturesnumriques" +=== Importer un PFX sur une autre machine ===
-$NewFolderName "Test-SitesSelected-Cert-OK"+
  
 +<code>
 +Import-PfxCertificate `
 +   -FilePath "fichier.pfx" `
 +   -CertStoreLocation Cert:\CurrentUser\My `  
 +   -Password (ConvertTo-SecureString -String "MotDePasseFort123!" -AsPlainText)
 +</code>
  
 +=== Générer une clé PKCS#8 ===
  
-$SitePath = "/sites/Signaturesnumriques" +  * Recharger le PFX 
-$NewFolderName = "Test-SitesSelected-OK"+
  
-############################################################ +<code> 
-# ÉTAPE 1 – OBTENIR UN TOKEN D’APPLICATION (CLIENT CREDENTIALS) +$pfxPath = "c:\temp\fichier.pfx" 
-############################################################+$pfxPassword = "TempPfxPassword!ChangeMe"
  
-Write-Host "Authentification par certificat…"+$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2( 
 +    $pfxPath, 
 +    $pfxPassword, 
 +    [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable 
 +
 +</code>
  
-$cert = Get-Item "Cert:\LocalMachine\My\$Thumbprint"+ * Récupérer la clé privée RSA
  
-$assertion [Microsoft.Identity.Client.ConfidentialClientApplicationBuilder]::Create($AppId). +<code> 
-    WithTenantId($TenantId). +$rsa = $cert.PrivateKey 
-    WithCertificate($cert)+</code>
-    Build()+
  
-$tokenResult = $assertion.AcquireTokenForClient(@("https://graph.microsoft.com/.default")). +  * Exporter la clé AU FORMAT PKCS#8
-    ExecuteAsync().GetAwaiter().GetResult()+
  
-$Headers @{ +<code> 
-    Authorization = "Bearer $($tokenResult.AccessToken)+# Récupère les paramètres 
-}+$params = $rsa.ExportParameters($true)
  
-Write-Host "Token d'application obtenu via certificat"+# Crée un RSA moderne 
 +$rsa2 = [System.Security.Cryptography.RSA]::Create() 
 +$rsa2.ImportParameters($params)
  
 +# Export PKCS#8
 +$pkcs8 = $rsa2.ExportPkcs8PrivateKey()
  
-############################################################ +$base64 = [System.Convert]::ToBase64String( 
-# ÉTAPE 2 – RÉCUPÉRER LE SITE SHAREPOINT PAR SON URL +    $pkcs8, 
-############################################################+    [System.Base64FormattingOptions]::InsertLineBreaks 
 +)
  
-Write-Host "Récupération du site SharePoint..." 
  
-$site Invoke-RestMethod ` +$pem @" 
-    -Method GET ` +-----BEGIN PRIVATE KEY----- 
-    -Uri "https://graph.microsoft.com/v1.0/sites/educvaladonlimogesfr.sharepoint.com:$SitePath" ` +$base64 
-    -Headers $Headers+-----END PRIVATE KEY----- 
 +"@
  
-$SiteId = $site.id+$pem | Set-Content ` 
 +  -Path C:\Temp\fichier.key ` 
 +  -Encoding ASCII 
 +</code>
  
-Write-Host "Site trouvé : $($site.displayName)" +=== Résumé .cer .pfx ===
-Write-Host "SiteId : $SiteId"+
  
-############################################################ +<WRAP center round info> 
-# ÉTAPE 3 – ATTRIBUER LA PERMISSION WRITE +Un fichier .cer contient uniquement la **clé publique du certificat**. Cela permet :  
-############################################################+  * de déclarer le certificat dans Entra ID 
 +  * permet à Microsoft de vérifier les signatures
  
-Write-Host "Attribution de la permission WRITE à l'application..."+La clé privée est déjà stockée dans Windows : 
 +  * dans **Cert:\LocalMachine\My** ou **Cert:\CurrentUser\My** 
 +  * aucun PFX n’est nécessaire tant que l'on se connecte depuis le PC où se trouve la clé privéeEn indiquant l'empreinte de la clé (thumbprint), cela permet de sélectionner la bonne clé privée.
  
-$permissionBody = @{ +Un fichier .cer ne permet pas : 
-    roles = @("write") +  * de s’authentifier 
-    grantedToIdentities = @( +  * de signer
-        @{ +
-            application = @{ +
-                id = $AppId +
-            } +
-        } +
-    ) +
-} | ConvertTo-Json -Depth 5+
  
-Invoke-RestMethod ` +Un fichier .pfx (format PFX PKCS#12) contient : 
-    -Method POST ` +  * la clé publique 
-    -Uri "https://graph.microsoft.com/v1.0/sites/$SiteId/permissions" ` +  * la clé privée 
-    -Headers $Headers ` +  * (optionnel) la chaîne de certificats 
-    -Body $permissionBody ` +  * et est protégé par une passphrase
-    -ContentType "application/json"+
  
-Write-Host "Permission Sites.Selected (write) appliquée"+C’est le seul format portable qui permet : 
 +  * d’importer un certificat avec clé privée 
 +  * d’authentifier une application sur une autre machine 
 +  * d’utiliser le certificat sur Linux / AWX / Docker / CI/CD
  
-############################################################ +^ Format    Contient  ^  Usage  ^ 
-# ÉTAPE 4 – TEST : CRÉATION D’UN DOSSIER DANS SHAREPOINT +|.cer|clé publique|Entra ID, SharePoint| 
-############################################################+|.pfx|clé publique + clé privée|Authentification| 
 +|.pfx + mdp|portable sécurisé|Serveur, automatisation| 
 +</WRAP>
  
-Write-Host "Test : création d’un dossier SharePoint..." 
  
-$folderBody @{ +==== Donner accès à l'application sur le site Sharepoint====
-    name $NewFolderName +
-    folder @{} +
-} | ConvertTo-Json+
  
-Invoke-RestMethod ` +   * l'administrateur doit donner l'accès au site voulu
-    -Method POST ` +
-    -Uri "https://graph.microsoft.com/v1.0/sites/$SiteId/drive/root/children"+
-    -Headers $Headers ` +
-    -Body $folderBody ` +
-    -ContentType "application/json"+
  
-Write-Host "SUCCÈS : le dossier '$NewFolderName' a été créé dans SharePoint"+<code> 
 +# deconnexion 
 +Disconnect-MgGraph 
 + 
 +# Connexion admin 
 +Connect-MgGraph -Scopes "Sites.FullControl.All" 
 + 
 +# Récupérer le site 
 +$site = Get-MgSite -SiteId "mondomaine.sharepoint.com:/sites/MonSite"
  
 +# Donner accès controle total à l'application (fullcontrol / read / write)
 +New-MgSitePermission `
 +  -SiteId $site.Id `
 +  -Roles "fullcontrol" `
 +  -GrantedToIdentities @{
 +      Application = @{
 +          Id = "ID application"
 +          DisplayName = "application"
 +      }
 +  }
 </code> </code>
 + 
 +  * Se reconnecter en AppOnly :
  
-  * Donner accès à l'application sur le site+<code> 
 +Connect-MgGraph `   
 +   -TenantId "<TENANT_ID>" `   
 +   -ClientId "<APP_ID>" `   
 +   -CertificateThumbprint "<THUMBPRINT>"  
 +</code> 
 + 
 +  Puis Tester l’accès au site précis:
  
 <code> <code>
-Grant-MgSitePermission -SiteId $site.Id -Roles "write" -GrantedToIdentities @{ application = @{ id = "APP_ID} }+Get-MgSite -SiteId "mondomaine.sharepoint.com:/sites/MonSite" 
 +</code>
  
-Grant-MgSitePermission ` 
-    -SiteId $site.Id ` 
-    -Roles "write" ` 
-    -GrantedToIdentities @{ application = @{ id = "APP_ID" } } 
  
 +==== Créer un dossier dans le site SharePoint ====
 +
 +  * Identifier le site SharePoint en itilisant le chemin direct :
 +
 +<code>
 +$site = Get-MgSite -SiteId "mondomaine.sharepoint.com:/sites/MonSite"
 +$site.Id
 +
 +=> Afficher le GUID du site du type :
 +xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
 </code> </code>
  
-  Tester l’accès avec Microsoft Graph  (avec client secret)+   Récupérer le drive du site (Documents: chaque site a une document library principale.
  
-Variables requises 
 <code> <code>
-$tenantId     "<TON_TENANT_ID>" +$drive Get-MgSiteDrive -SiteId $site.Id 
-$clientId     = "<APP_ID>" +$drive.Id 
-$clientSecret "<CLIENT_SECRET>" + 
-$siteId       = $site.Id+=> Affiche un DriveId 
 +Type : documentLibrary
 </code> </code>
  
-  * Obtenir un token avec l’application+  * Créer un dossier À LA RACINE (test simple).
  
 <code> <code>
-$tokenBody = @{ +New-MgDriveRootChild ` 
-    client_id     $clientId +  -DriveId $drive.Id ` 
-    scope         = "https://graph.microsoft.com/.default" +  -AdditionalProperties @{ 
-    client_secret = $clientSecret +      "name" "Test-Dossier" 
-    grant_type    = "client_credentials+      "folder" @{} 
-}+      "@microsoft.graph.conflictBehavior" = "rename
 +  }
  
-  *  Créer un dossier dans le site SharePoint+ 
 +=> Résultat attendu 
 +Id   : 01ABCDEF.... 
 +Name : Test-Dossier 
 +=> Dossier créé avec succès à vérifier dans SharePoint 
 +</code> 
 + 
 +  * lister les dossier à la racine
  
 <code> <code>
-$headers @{ Authorization = "Bearer $token" } +$items Get-MgDriveRootChild -DriveId $drive.Id 
-$body = '{ "name": "DossierTestCopilot", "folder": {} }'+</code>
  
-Invoke-RestMethod ` +  * Récupérer le dossier General 
-    -Uri "https://graph.microsoft.com/v1.0/sites/$siteId/drive/root/children" ` + 
-    -Headers $headers ` +<code> 
-    -Method POST ` +$parent = $items | Where-Object { $_.Name -eq "General
-    -Body $body ` +$parent.Id
-    -ContentType "application/json"+
 </code> </code>
  
 +  * création du sous-dossier
 +
 +<code>
 +New-MgDriveItemChild `
 +  -DriveId $drive.Id `
 +  -DriveItemId $parent.Id `
 +  -AdditionalProperties @{
 +      "name" = "Test-SousDossier"
 +      "folder" = @{}
 +      "@microsoft.graph.conflictBehavior" = "rename"
 +  }
 +</code>
 ==== Installer le module module PnP.PowerShell ==== ==== Installer le module module PnP.PowerShell ====
 PnP.PowerShell supporte : PnP.PowerShell supporte :
reseau/cloud/azure/configurerapppoursharepoint.1775421670.txt.gz · Dernière modification : 2026/04/05 22:41 de techer.charles_educ-valadon-limoges.fr