Gérer une application Microsoft Entra à l’aide de Microsoft Graph
Article
Votre application doit être inscrite dans l’ID Microsoft Entra pour que la plateforme d’identités Microsoft puisse l’autoriser à accéder aux données stockées dans le cloud Microsoft. Cette condition s’applique aux applications que vous développez vous-même, dont votre locataire est propriétaire ou auxquelles vous accédez via un abonnement actif.
De nombreux paramètres pour les applications sont enregistrés en tant qu’objets accessibles, mis à jour ou supprimés à l’aide de Microsoft Graph. Dans cet article, vous allez apprendre à utiliser Microsoft Graph pour gérer les détails des objets d’application et de principal de service, notamment les propriétés, les autorisations et les attributions de rôles.
Configuration requise
Pour tester les opérations de l’API, vous avez besoin des ressources et privilèges suivants :
Un locataire Microsoft Entra opérationnel.
Connectez-vous à l’Explorateur Graph en tant qu’utilisateur disposant des privilèges autorisés pour créer et gérer des applications dans le locataire.
Accordez-vous l’autorisation déléguée de privilège minimum indiquée pour l’opération.
Inscrire une application avec l’ID Microsoft Entra
La requête suivante crée une application en spécifiant uniquement la propriété displayName requise. Les valeurs par défaut sont affectées à d’autres propriétés.
Autorisation déléguée avec privilèges minimum : Application.ReadWrite.All.
POST https://graph.microsoft.com/v1.0/applications
Content-type: application/json
{
"displayName": "My application"
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new Application
{
DisplayName = "My application",
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Applications.PostAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewApplication()
displayName := "My application"
requestBody.SetDisplayName(&displayName)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
applications, err := graphClient.Applications().Post(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
Application application = new Application();
application.setDisplayName("My application");
Application result = graphClient.applications().post(application);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\Application;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new Application();
$requestBody->setDisplayName('My application');
$result = $graphServiceClient->applications()->post($requestBody)->wait();
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.application import Application
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = Application(
display_name = "My application",
)
result = await graph_client.applications.post(request_body)
La requête retourne une 201 Created réponse avec l’objet d’application dans le corps de la réponse. L’application se voit attribuer un ID unique pour les applications dans le locataire, et un appId globalement unique dans l’écosystème d’ID Microsoft Entra.
Créer un principal de service pour une application
Autorisation déléguée avec privilèges minimum : Application.ReadWrite.All.
POST https://graph.microsoft.com/v1.0/servicePrincipals
Content-type: application/json
{
"appId": "fc876dd1-6bcb-4304-b9b6-18ddf1526b62"
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new ServicePrincipal
{
AppId = "fc876dd1-6bcb-4304-b9b6-18ddf1526b62",
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.ServicePrincipals.PostAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewServicePrincipal()
appId := "fc876dd1-6bcb-4304-b9b6-18ddf1526b62"
requestBody.SetAppId(&appId)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
servicePrincipals, err := graphClient.ServicePrincipals().Post(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
ServicePrincipal servicePrincipal = new ServicePrincipal();
servicePrincipal.setAppId("fc876dd1-6bcb-4304-b9b6-18ddf1526b62");
ServicePrincipal result = graphClient.servicePrincipals().post(servicePrincipal);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\ServicePrincipal;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new ServicePrincipal();
$requestBody->setAppId('fc876dd1-6bcb-4304-b9b6-18ddf1526b62');
$result = $graphServiceClient->servicePrincipals()->post($requestBody)->wait();
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.service_principal import ServicePrincipal
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = ServicePrincipal(
app_id = "fc876dd1-6bcb-4304-b9b6-18ddf1526b62",
)
result = await graph_client.service_principals.post(request_body)
La requête retourne une 201 Created réponse avec l’objet principal de service dans le corps de la réponse.
Traitement d’une application ou d’un objet principal de service
Vous pouvez adresser une application ou un principal de service par son ID ou par son appId, où ID est appelé ID d’objet et appId est appelé ID d’application (client) dans le centre d’administration Microsoft Entra. Ces syntaxes sont prises en charge pour toutes les opérations HTTP CRUD sur les applications et les principaux de service.
Pour adresser une application ou un principal de service par son ID.
En outre, vous pouvez adresser un objet d’application unique à son uniqueName. Vous pouvez utiliser cette propriété pour créer une application avec le nom unique si elle n’existe pas, ou la mettre à jour si elle existe . une opération appelée « Upsert ».
Créez une application avec le uniqueName spécifié s’il n’existe pas ; sinon, mettez-la à jour.
Configurer d’autres propriétés de base pour votre application
Autorisation déléguée avec privilèges minimum : Application.ReadWrite.All.
Vous configurez les propriétés de base suivantes pour l’application.
Ajoutez des étiquettes pour la catégorisation dans l’organisation. Utilisez également la HideApp balise pour masquer l’application dans Mes applications et le lanceur Microsoft 365.
Ajoutez des informations de base, notamment le logo, les conditions d’utilisation et la déclaration de confidentialité.
Stocker les informations de contact sur l’application
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new Application
{
Tags = new List<string>
{
"HR",
"Payroll",
"HideApp",
},
Info = new InformationalUrl
{
LogoUrl = "https://cdn.pixabay.com/photo/2016/03/21/23/25/link-1271843_1280.png",
MarketingUrl = "https://www.contoso.com/app/marketing",
PrivacyStatementUrl = "https://www.contoso.com/app/privacy",
SupportUrl = "https://www.contoso.com/app/support",
TermsOfServiceUrl = "https://www.contoso.com/app/termsofservice",
},
Web = new WebApplication
{
HomePageUrl = "https://www.contoso.com/",
LogoutUrl = "https://www.contoso.com/frontchannel_logout",
RedirectUris = new List<string>
{
"https://localhost",
},
},
ServiceManagementReference = "Owners aliases: Finance @ contosofinance@contoso.com; The Phone Company HR consulting @ hronsite@thephone-company.com;",
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Applications["{application-id}"].PatchAsync(requestBody);
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
Application application = new Application();
LinkedList<String> tags = new LinkedList<String>();
tags.add("HR");
tags.add("Payroll");
tags.add("HideApp");
application.setTags(tags);
InformationalUrl info = new InformationalUrl();
info.setLogoUrl("https://cdn.pixabay.com/photo/2016/03/21/23/25/link-1271843_1280.png");
info.setMarketingUrl("https://www.contoso.com/app/marketing");
info.setPrivacyStatementUrl("https://www.contoso.com/app/privacy");
info.setSupportUrl("https://www.contoso.com/app/support");
info.setTermsOfServiceUrl("https://www.contoso.com/app/termsofservice");
application.setInfo(info);
WebApplication web = new WebApplication();
web.setHomePageUrl("https://www.contoso.com/");
web.setLogoutUrl("https://www.contoso.com/frontchannel_logout");
LinkedList<String> redirectUris = new LinkedList<String>();
redirectUris.add("https://localhost");
web.setRedirectUris(redirectUris);
application.setWeb(web);
application.setServiceManagementReference("Owners aliases: Finance @ contosofinance@contoso.com; The Phone Company HR consulting @ hronsite@thephone-company.com;");
Application result = graphClient.applications().byApplicationId("{application-id}").patch(application);
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.application import Application
from msgraph.generated.models.informational_url import InformationalUrl
from msgraph.generated.models.web_application import WebApplication
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = Application(
tags = [
"HR",
"Payroll",
"HideApp",
],
info = InformationalUrl(
logo_url = "https://cdn.pixabay.com/photo/2016/03/21/23/25/link-1271843_1280.png",
marketing_url = "https://www.contoso.com/app/marketing",
privacy_statement_url = "https://www.contoso.com/app/privacy",
support_url = "https://www.contoso.com/app/support",
terms_of_service_url = "https://www.contoso.com/app/termsofservice",
),
web = WebApplication(
home_page_url = "https://www.contoso.com/",
logout_url = "https://www.contoso.com/frontchannel_logout",
redirect_uris = [
"https://localhost",
],
),
service_management_reference = "Owners aliases: Finance @ contosofinance@contoso.com; The Phone Company HR consulting @ hronsite@thephone-company.com;",
)
result = await graph_client.applications.by_application_id('application-id').patch(request_body)
Limiter la connexion de l’application aux identités affectées uniquement
L’opération suivante limite les identités qui peuvent se connecter à une application uniquement à celles qui sont affectées à tous les rôles sur l’application.
Autorisation déléguée avec privilèges minimum : Application.ReadWrite.All.
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new ServicePrincipal
{
AppRoleAssignmentRequired = true,
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.ServicePrincipals["{servicePrincipal-id}"].PatchAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewServicePrincipal()
appRoleAssignmentRequired := true
requestBody.SetAppRoleAssignmentRequired(&appRoleAssignmentRequired)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
servicePrincipals, err := graphClient.ServicePrincipals().ByServicePrincipalId("servicePrincipal-id").Patch(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
ServicePrincipal servicePrincipal = new ServicePrincipal();
servicePrincipal.setAppRoleAssignmentRequired(true);
ServicePrincipal result = graphClient.servicePrincipals().byServicePrincipalId("{servicePrincipal-id}").patch(servicePrincipal);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\ServicePrincipal;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new ServicePrincipal();
$requestBody->setAppRoleAssignmentRequired(true);
$result = $graphServiceClient->servicePrincipals()->byServicePrincipalId('servicePrincipal-id')->patch($requestBody)->wait();
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.service_principal import ServicePrincipal
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = ServicePrincipal(
app_role_assignment_required = True,
)
result = await graph_client.service_principals.by_service_principal_id('servicePrincipal-id').patch(request_body)
Bien que vous puissiez attribuer des autorisations à une application via le Centre d’administration Microsoft Entra, vous attribuez également des autorisations via Microsoft Graph en mettant à jour la propriété requiredResourceAccess de l’objet d’application. Vous devez transmettre les autorisations existantes et nouvelles. La transmission de nouvelles autorisations uniquement remplace et supprime les autorisations existantes qui n’ont pas encore été consentées.
L’attribution d’autorisations ne les accorde pas automatiquement à l’application. Vous devez toujours accorder le consentement de l’administrateur à l’aide du Centre d’administration Microsoft Entra. Pour accorder des autorisations sans consentement interactif, consultez Accorder ou révoquer des autorisations d’API par programmation.
Autorisation déléguée avec privilèges minimum : Application.ReadWrite.All.
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new Application
{
RequiredResourceAccess = new List<RequiredResourceAccess>
{
new RequiredResourceAccess
{
ResourceAppId = "00000002-0000-0000-c000-000000000000",
ResourceAccess = new List<ResourceAccess>
{
new ResourceAccess
{
Id = Guid.Parse("311a71cc-e848-46a1-bdf8-97ff7156d8e6"),
Type = "Scope",
},
new ResourceAccess
{
Id = Guid.Parse("3afa6a7d-9b1a-42eb-948e-1650a849e176"),
Type = "Role",
},
},
},
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Applications["{application-id}"].PatchAsync(requestBody);
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
Application application = new Application();
LinkedList<RequiredResourceAccess> requiredResourceAccess = new LinkedList<RequiredResourceAccess>();
RequiredResourceAccess requiredResourceAccess1 = new RequiredResourceAccess();
requiredResourceAccess1.setResourceAppId("00000002-0000-0000-c000-000000000000");
LinkedList<ResourceAccess> resourceAccess = new LinkedList<ResourceAccess>();
ResourceAccess resourceAccess1 = new ResourceAccess();
resourceAccess1.setId(UUID.fromString("311a71cc-e848-46a1-bdf8-97ff7156d8e6"));
resourceAccess1.setType("Scope");
resourceAccess.add(resourceAccess1);
ResourceAccess resourceAccess2 = new ResourceAccess();
resourceAccess2.setId(UUID.fromString("3afa6a7d-9b1a-42eb-948e-1650a849e176"));
resourceAccess2.setType("Role");
resourceAccess.add(resourceAccess2);
requiredResourceAccess1.setResourceAccess(resourceAccess);
requiredResourceAccess.add(requiredResourceAccess1);
application.setRequiredResourceAccess(requiredResourceAccess);
Application result = graphClient.applications().byApplicationId("{application-id}").patch(application);
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.application import Application
from msgraph.generated.models.required_resource_access import RequiredResourceAccess
from msgraph.generated.models.resource_access import ResourceAccess
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = Application(
required_resource_access = [
RequiredResourceAccess(
resource_app_id = "00000002-0000-0000-c000-000000000000",
resource_access = [
ResourceAccess(
id = UUID("311a71cc-e848-46a1-bdf8-97ff7156d8e6"),
type = "Scope",
),
ResourceAccess(
id = UUID("3afa6a7d-9b1a-42eb-948e-1650a849e176"),
type = "Role",
),
],
),
],
)
result = await graph_client.applications.by_application_id('application-id').patch(request_body)
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new Application
{
AppRoles = new List<AppRole>
{
new AppRole
{
AllowedMemberTypes = new List<string>
{
"User",
"Application",
},
Description = "Survey.Read",
DisplayName = "Survey.Read",
Id = Guid.Parse("7a9ddfc4-cc8a-48ea-8275-8ecbffffd5a0"),
IsEnabled = false,
Origin = "Application",
Value = "Survey.Read",
},
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Applications["{application-id}"].PatchAsync(requestBody);
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
Application application = new Application();
LinkedList<AppRole> appRoles = new LinkedList<AppRole>();
AppRole appRole = new AppRole();
LinkedList<String> allowedMemberTypes = new LinkedList<String>();
allowedMemberTypes.add("User");
allowedMemberTypes.add("Application");
appRole.setAllowedMemberTypes(allowedMemberTypes);
appRole.setDescription("Survey.Read");
appRole.setDisplayName("Survey.Read");
appRole.setId(UUID.fromString("7a9ddfc4-cc8a-48ea-8275-8ecbffffd5a0"));
appRole.setIsEnabled(false);
appRole.setOrigin("Application");
appRole.setValue("Survey.Read");
appRoles.add(appRole);
application.setAppRoles(appRoles);
Application result = graphClient.applications().byApplicationId("{application-id}").patch(application);
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.application import Application
from msgraph.generated.models.app_role import AppRole
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = Application(
app_roles = [
AppRole(
allowed_member_types = [
"User",
"Application",
],
description = "Survey.Read",
display_name = "Survey.Read",
id = UUID("7a9ddfc4-cc8a-48ea-8275-8ecbffffd5a0"),
is_enabled = False,
origin = "Application",
value = "Survey.Read",
),
],
)
result = await graph_client.applications.by_application_id('application-id').patch(request_body)
Identifier les principaux de service et les principaux de service sans propriétaire avec un seul propriétaire
Autorisation déléguée avec privilèges minimum : Application.ReadWrite.All.
Cette demande nécessite que l’en-tête ConsistencyLevel soit défini sur eventual, car $count figure dans la demande. Pour plus d’informations sur l’utilisation de ConsistencyLevel et $count, consultez Fonctionnalités de requête avancées sur les objets d’annuaire.
Cette requête retourne également le nombre d’applications qui correspondent à la condition de filtre.
GET https://graph.microsoft.com/v1.0/servicePrincipals?$filter=owners/$count eq 0 or owners/$count eq 1&$count=true
ConsistencyLevel: eventual
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.ServicePrincipals.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "owners/$count eq 0 or owners/$count eq 1";
requestConfiguration.QueryParameters.Count = true;
requestConfiguration.Headers.Add("ConsistencyLevel", "eventual");
});
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
ServicePrincipalCollectionResponse result = graphClient.servicePrincipals().get(requestConfiguration -> {
requestConfiguration.queryParameters.filter = "owners/$count eq 0 or owners/$count eq 1";
requestConfiguration.queryParameters.count = true;
requestConfiguration.headers.add("ConsistencyLevel", "eventual");
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.service_principals.service_principals_request_builder import ServicePrincipalsRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = ServicePrincipalsRequestBuilder.ServicePrincipalsRequestBuilderGetQueryParameters(
filter = "owners/$count eq 0 or owners/$count eq 1",
count = True,
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
request_configuration.headers.add("ConsistencyLevel", "eventual")
result = await graph_client.service_principals.get(request_configuration = request_configuration)
POST https://graph.microsoft.com/v1.0/applications/7b45cf6d-9083-4eb2-92c4-a7e090f1fc40/owners/$ref
Content-Type: application/json
{
"@odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/8afc02cb-4d62-4dba-b536-9f6d73e9be26"
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new ReferenceCreate
{
OdataId = "https://graph.microsoft.com/v1.0/directoryObjects/8afc02cb-4d62-4dba-b536-9f6d73e9be26",
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
await graphClient.Applications["{application-id}"].Owners.Ref.PostAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewReferenceCreate()
odataId := "https://graph.microsoft.com/v1.0/directoryObjects/8afc02cb-4d62-4dba-b536-9f6d73e9be26"
requestBody.SetOdataId(&odataId)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
graphClient.Applications().ByApplicationId("application-id").Owners().Ref().Post(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
com.microsoft.graph.models.ReferenceCreate referenceCreate = new com.microsoft.graph.models.ReferenceCreate();
referenceCreate.setOdataId("https://graph.microsoft.com/v1.0/directoryObjects/8afc02cb-4d62-4dba-b536-9f6d73e9be26");
graphClient.applications().byApplicationId("{application-id}").owners().ref().post(referenceCreate);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\ReferenceCreate;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new ReferenceCreate();
$requestBody->setOdataId('https://graph.microsoft.com/v1.0/directoryObjects/8afc02cb-4d62-4dba-b536-9f6d73e9be26');
$graphServiceClient->applications()->byApplicationId('application-id')->owners()->ref()->post($requestBody)->wait();
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.reference_create import ReferenceCreate
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = ReferenceCreate(
odata_id = "https://graph.microsoft.com/v1.0/directoryObjects/8afc02cb-4d62-4dba-b536-9f6d73e9be26",
)
await graph_client.applications.by_application_id('application-id').owners.ref.post(request_body)
Affecter un propriétaire à un principal de service
Autorisation déléguée avec privilèges minimum : Application.ReadWrite.All.
La requête suivante fait référence au principal de service à l’aide de son appId. Vous pouvez également le référencer à l’aide de l’ID d’objet dans le modèle ../servicePrincipals/{bject ID}/owners/$ref.
8afc02cb-4d62-4dba-b536-9f6d73e9be26 est l’ID d’objet d’un utilisateur ou d’un principal de service.
POST https://graph.microsoft.com/v1.0/servicePrincipals(appId='46e6adf4-a9cf-4b60-9390-0ba6fb00bf6b')/owners/$ref
Content-Type: application/json
{
"@odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/8afc02cb-4d62-4dba-b536-9f6d73e9be26"
}
Verrouiller les propriétés sensibles pour les principaux de service
La fonctionnalité de verrouillage d’instance d’application vous permet de protéger les propriétés sensibles de vos applications multilocataires contre toute falsification non autorisée. Les propriétés suivantes de l’objet principal de service peuvent être verrouillées :
keyCredentials où le type d’utilisation est Sign ou Verify.
passwordCredentials où le type d’utilisation est Sign ou Verify.
propriété tokenEncryptionKeyId .
Vous gérez la fonctionnalité de verrouillage d’instance d’application via la propriété servicePrincipalLockConfiguration de l’objet application de l’application multilocataire.
Pour verrouiller toutes les propriétés sensibles d’un principal de service
Quand isEnabled et allProperties a la valeur true, même si d’autres propriétés de l’objet servicePrincipalLockConfiguration sont null, toutes les propriétés sensibles du principal de service sont verrouillées.
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Beta.Models;
var requestBody = new Application
{
ServicePrincipalLockConfiguration = new ServicePrincipalLockConfiguration
{
IsEnabled = true,
AllProperties = true,
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Applications["{application-id}"].PatchAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-beta-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewApplication()
servicePrincipalLockConfiguration := graphmodels.NewServicePrincipalLockConfiguration()
isEnabled := true
servicePrincipalLockConfiguration.SetIsEnabled(&isEnabled)
allProperties := true
servicePrincipalLockConfiguration.SetAllProperties(&allProperties)
requestBody.SetServicePrincipalLockConfiguration(servicePrincipalLockConfiguration)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
applications, err := graphClient.Applications().ByApplicationId("application-id").Patch(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
Application application = new Application();
ServicePrincipalLockConfiguration servicePrincipalLockConfiguration = new ServicePrincipalLockConfiguration();
servicePrincipalLockConfiguration.setIsEnabled(true);
servicePrincipalLockConfiguration.setAllProperties(true);
application.setServicePrincipalLockConfiguration(servicePrincipalLockConfiguration);
Application result = graphClient.applications().byApplicationId("{application-id}").patch(application);
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Models\Application;
use Microsoft\Graph\Beta\Generated\Models\ServicePrincipalLockConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new Application();
$servicePrincipalLockConfiguration = new ServicePrincipalLockConfiguration();
$servicePrincipalLockConfiguration->setIsEnabled(true);
$servicePrincipalLockConfiguration->setAllProperties(true);
$requestBody->setServicePrincipalLockConfiguration($servicePrincipalLockConfiguration);
$result = $graphServiceClient->applications()->byApplicationId('application-id')->patch($requestBody)->wait();
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.models.application import Application
from msgraph_beta.generated.models.service_principal_lock_configuration import ServicePrincipalLockConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = Application(
service_principal_lock_configuration = ServicePrincipalLockConfiguration(
is_enabled = True,
all_properties = True,
),
)
result = await graph_client.applications.by_application_id('application-id').patch(request_body)
Pour verrouiller des propriétés sensibles spécifiques d’un principal de service
L’exemple suivant verrouille les propriétés keyCredentials et passwordCredentials du principal de service et active la fonctionnalité de verrouillage d’instance d’application.
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Beta.Models;
var requestBody = new Application
{
ServicePrincipalLockConfiguration = new ServicePrincipalLockConfiguration
{
IsEnabled = true,
CredentialsWithUsageSign = true,
CredentialsWithUsageVerify = true,
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Applications["{application-id}"].PatchAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-beta-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewApplication()
servicePrincipalLockConfiguration := graphmodels.NewServicePrincipalLockConfiguration()
isEnabled := true
servicePrincipalLockConfiguration.SetIsEnabled(&isEnabled)
credentialsWithUsageSign := true
servicePrincipalLockConfiguration.SetCredentialsWithUsageSign(&credentialsWithUsageSign)
credentialsWithUsageVerify := true
servicePrincipalLockConfiguration.SetCredentialsWithUsageVerify(&credentialsWithUsageVerify)
requestBody.SetServicePrincipalLockConfiguration(servicePrincipalLockConfiguration)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
applications, err := graphClient.Applications().ByApplicationId("application-id").Patch(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
Application application = new Application();
ServicePrincipalLockConfiguration servicePrincipalLockConfiguration = new ServicePrincipalLockConfiguration();
servicePrincipalLockConfiguration.setIsEnabled(true);
servicePrincipalLockConfiguration.setCredentialsWithUsageSign(true);
servicePrincipalLockConfiguration.setCredentialsWithUsageVerify(true);
application.setServicePrincipalLockConfiguration(servicePrincipalLockConfiguration);
Application result = graphClient.applications().byApplicationId("{application-id}").patch(application);
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Models\Application;
use Microsoft\Graph\Beta\Generated\Models\ServicePrincipalLockConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new Application();
$servicePrincipalLockConfiguration = new ServicePrincipalLockConfiguration();
$servicePrincipalLockConfiguration->setIsEnabled(true);
$servicePrincipalLockConfiguration->setCredentialsWithUsageSign(true);
$servicePrincipalLockConfiguration->setCredentialsWithUsageVerify(true);
$requestBody->setServicePrincipalLockConfiguration($servicePrincipalLockConfiguration);
$result = $graphServiceClient->applications()->byApplicationId('application-id')->patch($requestBody)->wait();
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.models.application import Application
from msgraph_beta.generated.models.service_principal_lock_configuration import ServicePrincipalLockConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = Application(
service_principal_lock_configuration = ServicePrincipalLockConfiguration(
is_enabled = True,
credentials_with_usage_sign = True,
credentials_with_usage_verify = True,
),
)
result = await graph_client.applications.by_application_id('application-id').patch(request_body)
Configurer des autorités de certification approuvées pour les applications
Vous pouvez limiter l’utilisation des informations d’identification de certificat pour les applications de votre locataire aux certificats émis par les autorités de certification approuvées. Cette stratégie est appliquée lorsque vous ajoutez un certificat à une application et n’affecte pas les certificats existants, sauf s’ils sont pivotés. Lorsqu’une application tente de faire pivoter ses informations d’identification de certificat, elle passe par l’évaluation de la stratégie pour s’assurer que les informations d’identification ajoutées sont conformes à la restriction de l’autorité de certification approuvée.
Étape 1 : Créer une chaîne de certificats d’approbation
Autorisation déléguée avec privilèges minimum : AppCertTrustConfiguration.Read.All rôle Microsoft Entra avec privilèges minimum : Application Administrator
POST https://graph.microsoft.com/beta/certificateAuthorities/certificateBasedApplicationConfigurations
{
"displayName": "Trusted Certificate Chain of Trust for Contoso",
"description": "The Trusted Certificate Chain of Trust containing a certificate chain used by app policy, to only allow application certificates from selected issuer.",
"trustedCertificateAuthorities": [
{
"isRootAuthority": true,
"certificate": "MIIFVjCCAz6gAwIBAgIQJdrL...UyNDIyNTcwM1owPDE …="
},
{
"isRootAuthority": false,
"certificate": QAAAAAAWjABAQsFADA8M...UyNDIyNTcwM1o …="
}
]
}
La requête retourne un objet de réponse 200 OK . La réponse inclut l’ID de la chaîne de certificats de l’objet d’approbation. Supposons que l’ID soit eec5ba11-2fc0-4113-83a2-ed986ed13743.
Étape 2 : Affecter la chaîne de certificats d’approbation à une stratégie de gestion des applications
L’exemple suivant configure une stratégie pour s’assurer que seuls les certificats émis par l’autorité de certification intermédiaire définie à l’étape précédente peuvent être ajoutés aux applications dans le locataire.
L’objet applicationRestrictions>keyCredentials définit un restrictionType avec la valeur trustedCertificateAuthority, qui fait référence à l’ID créé. Étant donné que cette stratégie est appliquée à la stratégie de gestion des applications par défaut au niveau du locataire, elle est appliquée à toutes les applications créées dans le locataire et rejette les tentatives d’ajout de certificats non conformes dans le cadre des informations d’identification de certificat d’une application.
Cette stratégie garantit que seuls les certificats de l’autorité de certification intermédiaire spécifiée peuvent être ajoutés aux applications.
L’objet applicationRestrictions>keyCredentials définit un restrictionType sur trustedCertificateAuthority, référençant l’ID créé. Cette stratégie s’applique à toutes les applications du locataire, rejetant tout certificat non conforme.
Autorisation déléguée avec privilèges minimum : Policy.Read.ApplicationConfiguration rôle Microsoft Entra avec privilèges minimum : Security Administrator
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new TenantAppManagementPolicy
{
Id = "d015220e-9789-4e8e-bbcc-270fe419229d",
Description = "Lorem ipsum",
DisplayName = "Credential management policy",
IsEnabled = true,
ApplicationRestrictions = new AppManagementApplicationConfiguration
{
PasswordCredentials = new List<PasswordCredentialConfiguration>
{
new PasswordCredentialConfiguration
{
RestrictionType = AppCredentialRestrictionType.PasswordLifetime,
MaxLifetime = TimeSpan.Parse("P14D"),
RestrictForAppsCreatedAfterDateTime = DateTimeOffset.Parse("2020-01-01T07:00:00Z"),
},
},
KeyCredentials = new List<KeyCredentialConfiguration>
{
new KeyCredentialConfiguration
{
RestrictionType = AppKeyCredentialRestrictionType.AsymmetricKeyLifetime,
RestrictForAppsCreatedAfterDateTime = DateTimeOffset.Parse("2020-01-01T10:37:00Z"),
MaxLifetime = TimeSpan.Parse("P90D"),
},
new KeyCredentialConfiguration
{
RestrictionType = AppKeyCredentialRestrictionType.AsymmetricKeyLifetime,
RestrictForAppsCreatedAfterDateTime = DateTimeOffset.Parse("2019-10-19T10:37:00Z"),
AdditionalData = new Dictionary<string, object>
{
{
"certificateBasedApplicationConfigurationIds" , new List<string>
{
"eec5ba11-2fc0-4113-83a2-ed986ed13743",
}
},
},
},
},
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Policies.DefaultAppManagementPolicy.PatchAsync(requestBody);