Van toepassing op:
Werknemershuurders
Externe huurders (meer informatie)
Meer informatie over het configureren van de code voor uw daemontoepassing die web-API's aanroept.
Microsoft-bibliotheken die daemon-apps ondersteunen
De volgende Microsoft-bibliotheken ondersteunen daemon-apps:
1Universele licentievoorwaarden voor onlineservices zijn van toepassing op bibliotheken in openbare preview.
Daemon-toepassingen gebruiken toepassingsmachtigingen in plaats van gedelegeerde machtigingen. Het ondersteunde accounttype kan dus geen account zijn in een organisatiedirectory of een persoonlijk Microsoft-account (bijvoorbeeld Skype, Xbox, Outlook.com). Er is geen tenantbeheerder om toestemming te verlenen aan een daemontoepassing voor een persoonlijk Microsoft-account. U moet kiezen voor accounts in mijn organisatie of accounts in een willekeurige organisatie.
De instantie die is opgegeven in de toepassingsconfiguratie, moet de id van de ypur-tenant of een domeinnaam bevatten die is gekoppeld aan uw organisatie.
Zelfs als u een hulpprogramma voor meerdere tenants wilt aanbieden, moet u een tenant-id of domeinnaam gebruiken en nietcommon
of organizations
met dit proces, omdat de service niet betrouwbaar kan afleiden welke tenant moet worden gebruikt.
In Microsoft Authentication Libraries (MSAL) worden de clientreferenties (geheim of certificaat) doorgegeven als een parameter van de constructie van de vertrouwelijke clienttoepassing.
Belangrijk
Zelfs als uw toepassing een consoletoepassing is die als een service wordt uitgevoerd of een daemontoepassing is, moet het een vertrouwelijke clienttoepassing zijn.
Configuratiebestand
Het configuratiebestand definieert:
- Het cloudexemplaar en de tenant-id, die samen de instantie vormen.
- De client-ID die u hebt verkregen uit de registratie van de toepassing.
- Een clientgeheim of een certificaat.
Hier volgt een voorbeeld van het definiëren van de configuratie in een appsettings.json-bestand. Dit voorbeeld is afkomstig uit het codevoorbeeld van de .NET-console-daemon op 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]"
}
]
}
}
U levert een certificaat aan in plaats van de clientgeheim of workload-identiteitsfederatie-referenties.
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");
Configuratieparameters voor het Node.js daemon-voorbeeld bevinden zich in een .env-bestand:
# 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/
Wanneer u een vertrouwelijke client bouwt met clientgeheimen, is het configuratiebestand parameters.json in het Python-daemon-voorbeeld als volgt:
{
"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"
}
Wanneer u een vertrouwelijke client bouwt met certificaten, is het configuratiebestand parameters.json in het Python-daemon-voorbeeld als volgt:
{
"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"
}
Hier volgt een voorbeeld van het definiëren van de configuratie in een appsettings.json-bestand. Dit voorbeeld is afkomstig uit het codevoorbeeld van de .NET-console-daemon op 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]"
}
U geeft een ClientSecret
of een CertificateName
op. Deze instellingen zijn exclusief.
De MSAL-toepassing starten
Als u de MSAL-toepassing wilt starten, voegt u het MSAL-pakket toe, verwijst u ernaar of importeert u het (afhankelijk van de taal).
De constructie is verschillend, afhankelijk van of u clientgeheimen of certificaten gebruikt (of, als een geavanceerd scenario, ondertekende asserties).
Naar het pakket verwijzen
Verwijs naar het MSAL-pakket in uw toepassingscode.
Voeg het NuGet-pakket Microsoft.Identity.Web.TokenAcquisition toe aan uw toepassing.
Als u Microsoft Graph wilt aanroepen, kunt u ook het pakket Microsoft.Identity.Web.GraphServiceClient toevoegen.
Uw project kan als volgt zijn. Het appsettings.json-bestand moet worden gekopieerd naar de uitvoermap.
<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>
Voeg in het bestand Program.cs een using
instructie toe aan uw code om te verwijzen naar 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;
Installeer de pakketten door uit te voeren npm install
in de map waarin package.json
het bestand zich bevindt. Importeer vervolgens het msal-node
pakket:
const msal = require('@azure/msal-node');
import msal
import json
import sys
import logging
Voeg het NuGet-pakket Microsoft.Identity.Client toe aan uw toepassing en voeg vervolgens een using
-instructie toe aan uw code om ernaar te verwijzen.
In MSAL.NET wordt de vertrouwelijke clienttoepassing vertegenwoordigd door de IConfidentialClientApplication
-interface.
using Microsoft.Identity.Client;
IConfidentialClientApplication app;
Instantieer de vertrouwelijke clienttoepassing met een clientsleutel
Hier is de code om de vertrouwelijke cliënttoepassing te instantiëren met een cliëntgeheim:
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();
// ...
}
}
De configuratie wordt gelezen uit de 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
is een samenvoeging van het cloudexemplaar en de tenant-id, bijvoorbeeld https://login.microsoftonline.com/contoso.onmicrosoft.com
of https://login.microsoftonline.com/aaaabbbb-0000-cccc-1111-dddd2222eeee
. In het appsettings.json bestand dat wordt weergegeven in de sectie Configuratiebestand , worden exemplaar en tenant vertegenwoordigd door respectievelijk de Instance
en Tenant
waarden.
In het codevoorbeeld waaruit het vorige codefragment is genomen, is Authority
een eigenschap voor de klasse AuthenticationConfig en wordt als volgt gedefinieerd:
/// <summary>
/// URL of the authority
/// </summary>
public string Authority
{
get
{
return String.Format(CultureInfo.InvariantCulture, Instance, Tenant);
}
}
Initialiseer de vertrouwelijke clienttoepassing met een clientcertificaat
Dit is de code voor het bouwen van een toepassing met een certificaat:
De code zelf is precies hetzelfde. Het certificaat wordt beschreven in de configuratie.
Er zijn veel manieren om het certificaat op te halen. Zie voor meer informatie https://aka.ms/ms-id-web-certificates.
U kunt als volgt uw certificaat ophalen uit KeyVault. Microsoft-identiteit delegeert naar de DefaultAzureCredential van Azure Identity en gebruikte beheerde identiteit wanneer deze beschikbaar is voor toegang tot het certificaat vanuit KeyVault. U kunt lokaal fouten in uw toepassing opsporen, omdat deze vervolgens gebruikmaakt van uw referenties voor ontwikkelaars.
"ClientCredentials": [
{
"SourceType": "KeyVault",
"KeyVaultUrl": "https://yourKeyVaultUrl.vault.azure.net",
"KeyVaultCertificateName": "NameOfYourCertificate"
}
In MSAL Java zijn er twee bouwers om de vertrouwelijke clienttoepassing met certificaten te instantiëren.
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();
of
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);
Zie Certificaatreferenties gebruiken met MSAL Node voor meer informatie.
# 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();
Geavanceerd scenario: De vertrouwelijke cliënt-toepassing instantiëren met clientasserties
Naast het gebruik van een clientgeheim of certificaat kunnen vertrouwelijke clienttoepassingen ook hun identiteit bewijzen met behulp van clientverklaringen. Zie CredentialDescription voor meer informatie.
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);
Zie Het ConfidentialClientApplication-object initialiseren voor meer informatie.
In MSAL Python kunt u client claims opgeven met behulp van de claims die door de persoonlijke sleutel van deze ConfidentialClientApplication
worden ondertekend.
# 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
)
Zie de MSAL Python-referentiedocumentatie voor ConfidentialClientApplication voor meer informatie.
In plaats van een clientgeheim of certificaat kan de vertrouwelijke clienttoepassing ook de identiteit aantonen met behulp van clientasserties.
MSAL.NET heeft twee methoden om ondertekende asserties te bieden aan de vertrouwelijke client-app:
.WithClientAssertion()
.WithClientClaims()
Als u WithClientAssertion
gebruikt, geeft u een ondertekende JWT op. Dit geavanceerde scenario wordt beschreven in Clientasserties.
string signedClientAssertion = ComputeAssertion();
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithClientAssertion(signedClientAssertion)
.Build();
Wanneer u gebruikt WithClientClaims
, produceert MSAL.NET een ondertekende assertie die de claims bevat die worden verwacht door Microsoft Entra ID, plus aanvullende clientclaims die u wilt verzenden.
Deze code laat zien hoe u dit doet:
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();
Zie Clientasserties voor meer informatie.
Volgende stappen