S’applique à :
Locataires de main-d’œuvre (en savoir plus)
Découvrez comment configurer le code de votre application démon qui appelle des API web.
Bibliothèques Microsoft prenant en charge les applications démon
Les bibliothèques Microsoft suivantes prennent en charge les applications démon :
1Les termes du contrat de licence universelle pour les services en ligne s’appliquent aux bibliothèques en préversion publique.
Les applications démon utilisent des permissions d’application plutôt que des permissions déléguées. Le type de compte pris en charge ne peut donc pas être un compte dans un annuaire organisationnel ou un compte Microsoft personnel (par exemple, Skype, Xbox, Outlook.com). Aucun administrateur client n’octroie de consentement à une application démon pour un compte Microsoft personnel. Vous devez choisir des comptes dans mon organisation ou des comptes dans une organisation.
L’autorité spécifiée dans la configuration de l’application doit inclure l’ID de locataire ypur ou un nom de domaine associé à votre organisation.
Même si vous souhaitez fournir un outil multilocataire, vous devez utiliser un ID de locataire ou un nom de domaine, et non pascommon ou organizations avec ce flux, car le service ne peut pas inférer de manière fiable le locataire à utiliser.
Dans les bibliothèques d’authentification Microsoft (MSAL), les informations d’identification du client (secret ou certificat) sont passées en tant que paramètre de la construction de l’application cliente confidentielle.
Important
Même si votre application est une application console qui s’exécute en tant que service, s’il s’agit d’une application démon, il devra s’agir d’une application cliente confidentielle.
Fichier de configuration
Le fichier de configuration définit les éléments suivants :
- L’instance cloud et l’ID de locataire, qui composent ensemble l’autorité.
- ID client que vous avez obtenu à partir de l’inscription de l’application ;
- secret client ou certificat.
Voici un exemple de définition de la configuration dans un fichier appsettings.json. Cet exemple est extrait de l'exemple de code démon de console .NET sur GitHub.
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "[Enter here the tenantID or domain name for your Azure AD tenant]",
"ClientId": "[Enter here the ClientId for your application]",
"ClientCredentials": [
{
"SourceType": "ClientSecret",
"ClientSecret": "[Enter here a client secret for your application]"
}
]
}
}
Vous fournissez un certificat au lieu de la clé secrète client ou des informations d’identification de fédération d’identité de charge de travail .
private final static String CLIENT_ID = "";
private final static String AUTHORITY = "https://login.microsoftonline.com/<tenant>/";
private final static String CLIENT_SECRET = "";
private final static Set<String> SCOPE = Collections.singleton("https://graph.microsoft.com/.default");
Les paramètres de configuration de l'exemple de démon Node.js se trouvent dans un fichier .env :
# Credentials
TENANT_ID=Enter_the_Tenant_Info_Here
CLIENT_ID=Enter_the_Application_Id_Here
// You provide either a ClientSecret or a CertificateConfiguration, or a ClientAssertion. These settings are exclusive
CLIENT_SECRET=Enter_the_Client_Secret_Here
CERTIFICATE_THUMBPRINT=Enter_the_certificate_thumbprint_Here
CERTIFICATE_PRIVATE_KEY=Enter_the_certificate_private_key_Here
CLIENT_ASSERTION=Enter_the_Assertion_String_Here
# Endpoints
// the Azure AD endpoint is the authority endpoint for token issuance
AAD_ENDPOINT=Enter_the_Cloud_Instance_Id_Here // https://login.microsoftonline.com/
// the graph endpoint is the application ID URI of Microsoft Graph
GRAPH_ENDPOINT=Enter_the_Graph_Endpoint_Here // https://graph.microsoft.com/
Quand vous générez un client confidentiel avec des secrets client, le fichier config parameters.json de l’exemple Démon Python se présente comme suit :
{
"authority": "https://login.microsoftonline.com/<your_tenant_id>",
"client_id": "your_client_id",
"scope": [ "https://graph.microsoft.com/.default" ],
"secret": "The secret generated by Azure AD during your confidential app registration",
"endpoint": "https://graph.microsoft.com/v1.0/users"
}
Quand vous générez un client confidentiel avec des certificats, le fichier config parameters.json de l’exemple Démon Python se présente comme suit :
{
"authority": "https://login.microsoftonline.com/<your_tenant_id>",
"client_id": "your_client_id",
"scope": [ "https://graph.microsoft.com/.default" ],
"thumbprint": "790E... The thumbprint generated by Azure AD when you upload your public cert",
"private_key_file": "server.pem",
"endpoint": "https://graph.microsoft.com/v1.0/users"
}
Voici un exemple de définition de la configuration dans un fichier appsettings.json. Cet exemple est extrait de l'exemple de code démon de console .NET sur GitHub.
{
"Instance": "https://login.microsoftonline.com/{0}",
"Tenant": "[Enter here the tenantID or domain name for your Azure AD tenant]",
"ClientId": "[Enter here the ClientId for your application]",
"ClientSecret": "[Enter here a client secret for your application]",
"CertificateName": "[Or instead of client secret: Enter here the name of a certificate (from the user cert store) as registered with your application]"
}
Vous fournissez un paramètre ClientSecret ou CertificateName. Ces paramètres sont exclusifs.
Instancier l’application MSAL
Pour instancier l’application MSAL, ajoutez, référencez ou importez le package MSAL (selon le langage de programmation).
La construction est différente selon que vous utilisez des certificats ou des secrets clients (ou, en tant que scénario avancé, des assertions signées).
Référencer le package
Faites référence au package MSAL dans le code de votre application.
Ajoutez le package NuGet Microsoft.Identity.Web.TokenAcquisition à votre application.
Sinon, si vous souhaitez appeler Microsoft Graph, ajoutez le package Microsoft.Identity.Web.GraphServiceClient.
Votre projet peut être comme suit. Le fichier appsettings.json doit être copié dans le répertoire de sortie.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<RootNamespace>daemon_console</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Identity.Web.GraphServiceClient" Version="2.12.2" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
Dans le fichier Program.cs, ajoutez une using directive dans votre code pour référencer Microsoft.Identity.Web.
using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;
import com.microsoft.aad.msal4j.ClientCredentialFactory;
import com.microsoft.aad.msal4j.ClientCredentialParameters;
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import com.microsoft.aad.msal4j.IClientCredential;
import com.microsoft.aad.msal4j.MsalException;
import com.microsoft.aad.msal4j.SilentParameters;
Installez les packages en exécutant npm install dans le dossier où se trouve le fichier package.json. Importez ensuite le package msal-node :
const msal = require('@azure/msal-node');
import msal
import json
import sys
import logging
Ajoutez le package NuGet Microsoft.Identity.Client à votre application, puis ajoutez une directive using dans votre code pour le référencer.
Dans MSAL.NET, l’application cliente confidentielle est représentée par l’interface IConfidentialClientApplication.
using Microsoft.Identity.Client;
IConfidentialClientApplication app;
Instancier l’application cliente confidentielle avec un secret client
Voici le code permettant d’instancier l’application cliente confidentielle avec un secret client :
class Program
{
static async Task Main(string[] _)
{
// Get the Token acquirer factory instance. By default it reads an appsettings.json
// file if it exists in the same folder as the app (make sure that the
// "Copy to Output Directory" property of the appsettings.json file is "Copy if newer").
TokenAcquirerFactory tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();
// Configure the application options to be read from the configuration
// and add the services you need (Graph, token cache)
IServiceCollection services = tokenAcquirerFactory.Services;
services.AddMicrosoftGraph();
// By default, you get an in-memory token cache.
// For more token cache serialization options, see https://aka.ms/msal-net-token-cache-serialization
// Resolve the dependency injection.
var serviceProvider = tokenAcquirerFactory.Build();
// ...
}
}
La configuration est lue à partir du fichier appsettings.json :
IClientCredential credential = ClientCredentialFactory.createFromSecret(CLIENT_SECRET);
ConfidentialClientApplication cca =
ConfidentialClientApplication
.builder(CLIENT_ID, credential)
.authority(AUTHORITY)
.build();
const msalConfig = {
auth: {
clientId: process.env.CLIENT_ID,
authority: process.env.AAD_ENDPOINT + process.env.TENANT_ID,
clientSecret: process.env.CLIENT_SECRET,
}
};
const apiConfig = {
uri: process.env.GRAPH_ENDPOINT + 'v1.0/users',
};
const tokenRequest = {
scopes: [process.env.GRAPH_ENDPOINT + '.default'],
};
const cca = new msal.ConfidentialClientApplication(msalConfig);
# Pass the parameters.json file as an argument to this Python script. E.g.: python your_py_file.py parameters.json
config = json.load(open(sys.argv[1]))
# Create a preferably long-lived app instance that maintains a token cache.
app = msal.ConfidentialClientApplication(
config["client_id"], authority=config["authority"],
client_credential=config["secret"],
# token_cache=... # Default cache is in memory only.
# You can learn how to use SerializableTokenCache from
# https://msal-python.rtfd.io/en/latest/#msal.SerializableTokenCache
)
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithClientSecret(config.ClientSecret)
.WithAuthority(new Uri(config.Authority))
.Build();
Authority est une concaténation de l’instance cloud et de l’ID de locataire, par exemple https://login.microsoftonline.com/contoso.onmicrosoft.com ou https://login.microsoftonline.com/aaaabbbb-0000-cccc-1111-dddd2222eeee. Dans le fichier appsettings.json indiqué dans la section Fichier de configuration, les instances et les abonnés sont représentés respectivement par les valeurs Instance et Tenant.
Dans l’exemple de code d’où l’extrait de code précédent est tiré, Authority est une propriété dans la classe AuthenticationConfig et elle est définie comme suit :
/// <summary>
/// URL of the authority
/// </summary>
public string Authority
{
get
{
return String.Format(CultureInfo.InvariantCulture, Instance, Tenant);
}
}
Instancier l’application cliente confidentielle avec un certificat client
Voici le code permettant de générer une application avec un certificat :
Le code en lui-même est exactement pareil. Le certificat est décrit dans la configuration.
Il existe de nombreuses façons d’obtenir le certificat. Pour plus d'informations, voir https://aka.ms/ms-id-web-certificates.
Voici comment vous pouvez obtenir votre certificat à partir de KeyVault. L’identité Microsoft délègue à DefaultAzureCredential de Azure Identity et utilise l’identité managée lorsqu’elle est disponible pour accéder au certificat à partir de KeyVault. Vous pouvez déboguer votre application localement, car elle utilise ensuite vos informations d’identification de développeur.
"ClientCredentials": [
{
"SourceType": "KeyVault",
"KeyVaultUrl": "https://yourKeyVaultUrl.vault.azure.net",
"KeyVaultCertificateName": "NameOfYourCertificate"
}
Dans MSAL Java, il existe deux générateurs permettant d’instancier l’application cliente confidentielle avec des certificats :
InputStream pkcs12Certificate = ... ; /* Containing PCKS12-formatted certificate*/
string certificatePassword = ... ; /* Contains the password to access the certificate */
IClientCredential credential = ClientCredentialFactory.createFromCertificate(pkcs12Certificate, certificatePassword);
ConfidentialClientApplication cca =
ConfidentialClientApplication
.builder(CLIENT_ID, credential)
.authority(AUTHORITY)
.build();
or
PrivateKey key = getPrivateKey(); /* RSA private key to sign the assertion */
X509Certificate publicCertificate = getPublicCertificate(); /* x509 public certificate used as a thumbprint */
IClientCredential credential = ClientCredentialFactory.createFromCertificate(key, publicCertificate);
ConfidentialClientApplication cca =
ConfidentialClientApplication
.builder(CLIENT_ID, credential)
.authority(AUTHORITY)
.build();
const config = {
auth: {
clientId: process.env.CLIENT_ID,
authority: process.env.AAD_ENDPOINT + process.env.TENANT_ID,
clientCertificate: {
thumbprint: process.env.CERTIFICATE_THUMBPRINT, // a 40-digit hexadecimal string
privateKey: process.env.CERTIFICATE_PRIVATE_KEY,
}
}
};
// Create an MSAL application object
const cca = new msal.ConfidentialClientApplication(config);
Pour plus d’informations, consultez Utiliser les informations d’identification de certificat avec MSAL Node.
# Pass the parameters.json file as an argument to this Python script. E.g.: python your_py_file.py parameters.json
config = json.load(open(sys.argv[1]))
# Create a preferably long-lived app instance that maintains a token cache.
app = msal.ConfidentialClientApplication(
config["client_id"], authority=config["authority"],
client_credential={"thumbprint": config["thumbprint"], "private_key": open(config['private_key_file']).read()},
# token_cache=... # Default cache is in memory only.
# You can learn how to use SerializableTokenCache from
# https://msal-python.rtfd.io/en/latest/#msal.SerializableTokenCache
)
X509Certificate2 certificate = ReadCertificate(config.CertificateName);
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithCertificate(certificate)
.WithAuthority(new Uri(config.Authority))
.Build();
Scénario avancé : Instancier l’application cliente confidentielle avec des assertions clientes
Outre l’utilisation d’une clé secrète client ou d’un certificat client, les applications clientes confidentielles peuvent également prouver leur identité en utilisant des assertions client. Voir CredentialDescription pour les détails.
IClientCredential credential = ClientCredentialFactory.createFromClientAssertion(assertion);
ConfidentialClientApplication cca =
ConfidentialClientApplication
.builder(CLIENT_ID, credential)
.authority(AUTHORITY)
.build();
const clientConfig = {
auth: {
clientId: process.env.CLIENT_ID,
authority: process.env.AAD_ENDPOINT + process.env.TENANT_ID,
clientAssertion: process.env.CLIENT_ASSERTION
}
};
const cca = new msal.ConfidentialClientApplication(clientConfig);
Pour plus d’informations, consultez Initialiser l’objet ConfidentialClientApplication.
Dans MSAL Python, vous pouvez fournir des revendications de client à l’aide des revendications qui seront signées par la clé privée de cette ConfidentialClientApplication.
# Pass the parameters.json file as an argument to this Python script. E.g.: python your_py_file.py parameters.json
config = json.load(open(sys.argv[1]))
# Create a preferably long-lived app instance that maintains a token cache.
app = msal.ConfidentialClientApplication(
config["client_id"], authority=config["authority"],
client_credential={"thumbprint": config["thumbprint"], "private_key": open(config['private_key_file']).read()},
client_claims = {"client_ip": "x.x.x.x"}
# token_cache=... # Default cache is in memory only.
# You can learn how to use SerializableTokenCache from
# https://msal-python.rtfd.io/en/latest/#msal.SerializableTokenCache
)
Pour plus d’informations, consultez la documentation de référence de MSAL Python relative à ConfidentialClientApplication.
À la place d’un secret client ou d’un certificat, l’application cliente confidentielle peut aussi prouver son identité à l’aide d’assertions clientes.
MSAL.NET possède deux méthodes pour fournir des assertions signées à l’application cliente confidentielle :
.WithClientAssertion()
.WithClientClaims()
Lorsque vous utilisez WithClientAssertion, fournissez un jeton JWT signé. Ce scénario avancé est détaillé dans Assertions clientes.
string signedClientAssertion = ComputeAssertion();
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithClientAssertion(signedClientAssertion)
.Build();
Lorsque vous utilisez WithClientClaims, MSAL.NET génère une assertion signée qui contient les revendications attendues par Microsoft Entra ID, en plus des revendications clientes supplémentaires que vous souhaitez envoyer.
Ce code illustre comment procéder :
string ipAddress = "192.168.1.2";
var claims = new Dictionary<string, string> { { "client_ip", ipAddress } };
X509Certificate2 certificate = ReadCertificate(config.CertificateName);
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithAuthority(new Uri(config.Authority))
.WithClientClaims(certificate, claims)
.Build();
Encore une fois, pour plus d’informations, consultez Assertions clientes.
Étapes suivantes