Share via


Accorder le consentement au nom d’un seul utilisateur à l’aide de PowerShell

Dans cet article, vous découvrirez comment accorder le consentement au nom d’un utilisateur unique à l’aide de PowerShell.

Lorsqu’un utilisateur accorde son consentement pour lui-même, les événements suivants se produisent plus souvent :

  1. Un principal de service est créé pour l’application cliente, s’il n’en existe pas encore. Un principal de service est l’instance d’une application ou d’un service dans votre locataire Microsoft Entra. L’accès accordé à l’application ou au service est associé à cet objet de principal de service.

  2. Pour chaque API à laquelle l’application doit pouvoir accéder, un octroi d’autorisation déléguée à cette API est créé pour les autorisations dont l’application a besoin. L’accès est accordé pour le compte de l’utilisateur. Un octroi d’autorisation déléguée autorise une application à accéder à une API pour le compte d’un utilisateur, quand cet utilisateur s’est connecté.

  3. L’application cliente est affectée à l’utilisateur. L’attribution de l’application à l’utilisateur garantit que celle-çi est listée dans le portail Mes applications pour cet utilisateur. L’utilisateur peut passer en revue et révoquer l’accès accordé en son nom à partir de son portail Mes applications.

Prérequis

Pour accorder le consentement à une application au nom d’un seul utilisateur, vous avez besoin de ce qui suit :

  • Un compte d’utilisateur avec Administrateur de rôle privilégié, Administrateur d’applications ou Administrateur d’applications cloud

Avant de commencer, enregistrez les détails suivants à partir du centre d’administration Microsoft Entra :

  • L’ID de l’application à laquelle vous accordez le consentement. Dans le cadre de cet article, nous l’appelerons application cliente.
  • Les autorisations d’API requises par l’application cliente. Découvrez l’ID d’application de l’API et les ID d’autorisation ou valeurs des revendications.
  • Le nom d’utilisateur ou l’ID d’objet correspondant à l’utilisateur au nom duquel l’accès est accordé.

Pour cet exemple, nous allons utiliser Microsoft Graph PowerShell pour accorder le consentement au nom d’un seul utilisateur. L’application cliente est Microsoft Graph Explorer et nous accordons l’accès à l’API Microsoft Graph.

Pour accorder le consentement à une application au nom d’un utilisateur à l’aide de Microsoft Graph PowerShell, vous devez vous connecter comme au moins une Administrateur d’application cloud.

# The app for which consent is being granted. In this example, we're granting access
# to Microsoft Graph Explorer, an application published by Microsoft.
$clientAppId = "de8bc8b5-d9f9-48b1-a8ad-b748da725064" # Microsoft Graph Explorer

# The API to which access will be granted. Microsoft Graph Explorer makes API 
# requests to the Microsoft Graph API, so we'll use that here.
$resourceAppId = "00000003-0000-0000-c000-000000000000" # Microsoft Graph API

# The permissions to grant. Here we're including "openid", "profile", "User.Read"
# and "offline_access" (for basic sign-in), as well as "User.ReadBasic.All" (for 
# reading other users' basic profile).
$permissions = @("openid", "profile", "offline_access", "User.Read", "User.ReadBasic.All")

# The user on behalf of whom access will be granted. The app will be able to access 
# the API on behalf of this user.
$userUpnOrId = "user@example.com"

# Step 0. Connect to Microsoft Graph PowerShell. We need User.ReadBasic.All to get
#    users' IDs, Application.ReadWrite.All to list and create service principals, 
#    DelegatedPermissionGrant.ReadWrite.All to create delegated permission grants, 
#    and AppRoleAssignment.ReadWrite.All to assign an app role.
#    WARNING: These are high-privilege permissions!
Connect-MgGraph -Scopes ("User.ReadBasic.All Application.ReadWrite.All " `
                        + "DelegatedPermissionGrant.ReadWrite.All " `
                        + "AppRoleAssignment.ReadWrite.All")

# Step 1. Check if a service principal exists for the client application. 
#     If one doesn't exist, create it.
$clientSp = Get-MgServicePrincipal -Filter "appId eq '$($clientAppId)'"
if (-not $clientSp) {
   $clientSp = New-MgServicePrincipal -AppId $clientAppId
}

# Step 2. Create a delegated permission that grants the client app access to the
#     API, on behalf of the user. (This example assumes that an existing delegated 
#     permission grant does not already exist, in which case it would be necessary 
#     to update the existing grant, rather than create a new one.)
$user = Get-MgUser -UserId $userUpnOrId
$resourceSp = Get-MgServicePrincipal -Filter "appId eq '$($resourceAppId)'"
$scopeToGrant = $permissions -join " "
$grant = New-MgOauth2PermissionGrant -ResourceId $resourceSp.Id `
                                     -Scope $scopeToGrant `
                                     -ClientId $clientSp.Id `
                                     -ConsentType "Principal" `
                                     -PrincipalId $user.Id

# Step 3. Assign the app to the user. This ensures that the user can sign in if assignment
#     is required, and ensures that the app shows up under the user's My Apps portal.
if ($clientSp.AppRoles | ? { $_.AllowedMemberTypes -contains "User" }) {
    Write-Warning ("A default app role assignment cannot be created because the " `
                 + "client application exposes user-assignable app roles. You must " `
                 + "assign the user a specific app role for the app to be listed " `
                 + "in the user's My Apps access panel.")
} else {
    # The app role ID 00000000-0000-0000-0000-000000000000 is the default app role
    # indicating that the app is assigned to the user, but not for any specific 
    # app role.
    $assignment = New-MgServicePrincipalAppRoleAssignedTo `
          -ServicePrincipalId $clientSp.Id `
          -ResourceId $clientSp.Id `
          -PrincipalId $user.Id `
          -AppRoleId "00000000-0000-0000-0000-000000000000"
}

Pour accorder le consentement à une application au nom d’un utilisateur à l’aide de l’API Microsoft Graph, connectez-vous à Explorateur graphique comme au moins une Administrateur d’application cloud.

Vous devez consentir aux autorisations suivantes :

Application.ReadWrite.All, Directory.ReadWrite.All, DelegatedPermissionGrant.ReadWrite.All.

Dans l’exemple suivant, vous allez accorder des autorisations déléguées définies par une API de ressources à une application d’entreprise cliente au nom d’un utilisateur unique.

Dans l’exemple, l’application d’entreprise de ressources est Microsoft Graph de l’ID objet 11112222-bbbb-3333-cccc-4444dddd5555. Microsoft Graph définit les autorisations déléguées, User.Read.All et Group.Read.All. ConsentType est Principal, ce qui indique que vous consentez pour le compte d’un utilisateur du locataire. L’ID objet de l’application d’entreprise cliente est 00001111-aaaa-2222-bbbb-3333cccc4444. PrincipalId de l’utilisateur est aaaaaaaa-bbbb-cccc-1111-222222222222.

Attention

Soyez prudent ! Les autorisations accordées programmatiquement ne font pas l’objet d’une révision ou d’une confirmation. Elles prennent effet immédiatement.

  1. Récupérez toutes les autorisations déléguées définies par Microsoft Graph (l’application de ressources) dans votre application de locataire. Identifiez les autorisations déléguées que vous souhaitez accorder à l’application cliente. Dans cet exemple, les autorisations de délégation sont User.Read.All et Group.Read.All

    GET https://graph.microsoft.com/v1.0/servicePrincipals?$filter=displayName eq 'Microsoft Graph'&$select=id,displayName,appId,oauth2PermissionScopes
    
  2. Accordez les autorisations déléguées à l’application d’entreprise cliente pour le compte de l’utilisateur en exécutant la requête suivante.

    POST https://graph.microsoft.com/v1.0/oauth2PermissionGrants
    
    Request body
    {
       "clientId": "00001111-aaaa-2222-bbbb-3333cccc4444",
       "consentType": "Principal",
       "resourceId": "11112222-bbbb-3333-cccc-4444dddd5555",
       "principalId": "aaaaaaaa-bbbb-cccc-1111-222222222222",
       "scope": "User.Read.All Group.Read.All"
    }
    
  3. Confirmez que vous avez accordé le consentement de l’utilisateur en exécutant la requête suivante.

    GET https://graph.microsoft.com/v1.0/oauth2PermissionGrants?$filter=clientId eq '00001111-aaaa-2222-bbbb-3333cccc4444' and consentType eq 'Principal'
    
  4. Attribuez l’application à l’utilisateur. Cette affectation garantit que l’utilisateur peut se connecter si elle est requise et que l’application est disponible via le portail Mes applications de l’utilisateur. Dans l’exemple suivant, resourceIdreprésente l’application cliente à laquelle l’utilisateur est affecté. L’utilisateur se verra attribuer le rôle d’application par défaut, qui est 00000000-0000-0000-0000-000000000000.

        POST /servicePrincipals/resource-servicePrincipal-id/appRoleAssignedTo
    
        {
        "principalId": "aaaaaaaa-bbbb-cccc-1111-222222222222",
        "resourceId": "a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1",
        "appRoleId": "00000000-0000-0000-0000-000000000000"
        }
    

Étapes suivantes