適用於:
員工租戶 (瞭解更多資訊)
了解如何設定精靈應用程式的程式碼,以呼叫 Web API。
支援精靈應用程式的 Microsoft 程式庫
下列 Microsoft 程式庫支援精靈應用程式:
1在線服務的通用授權條款適用於公開預覽中的連結庫。
精靈應用程式會使用應用程式許可權,而不是委派權限。 因此,其所支援的帳戶類型不可以是任何組織目錄中的帳戶,也不可以為任何個人的 Microsoft 帳戶 (例如 Skype、Xbox、Outlook.com)。 沒有租用戶系統管理員可以將精靈應用程式的同意權限授與 Microsoft 個人帳戶。 您需要選擇 在我組織中的帳戶 或 在任何組織中的帳戶。
在應用程式組態中指定的授權應包括你的租戶 ID 或與組織相關聯的網域名稱。
即使您想要提供多租戶工具,您也應該使用租戶 ID 或網域名稱,而不是使用此流程,因為服務無法可靠地推斷應使用哪一個租戶。
在 Microsoft 驗證程式庫(MSAL)中,用戶端認證(秘密或憑證)被作為參數傳遞給機密用戶端應用程式。
重要
即使您的應用程式是以服務方式執行的主控台應用程式,如果該應用程式為精靈應用程式,則一定會是機密用戶端應用程式。
組態檔
組態檔會定義以下項目:
- 雲端執行個體和租用戶識別碼,兩者一起就會構成「授權單位」。
- 應用程式註冊所提供的用戶端識別碼。
- 選擇用戶端密碼或憑證其中一項。
以下是在 appsettings.json 檔案中定義設定的範例。 此範例取自 GitHub 上的 .NET 主控台精靈程式碼範例。
{
"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]"
}
]
}
}
您提供的是憑證,而不是用戶端密碼,或是工作負載身分識別同盟認證。
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");
您可以在 .env 檔案中找到 Node.js 精靈範例的設定參數:
# 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/
當您透過用戶端密碼建立機密用戶端時,Python 精靈範例中的 parameters.json 組態檔內容如下:
{
"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"
}
當您使用憑證來建立機密用戶端時,Python 精靈範例中的 parameters.json 組態檔內容如下:
{
"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"
}
以下是在 appsettings.json 檔案中定義設定的範例。 此範例取自 GitHub 上的 .NET 主控台精靈程式碼範例。
{
"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]"
}
您可以提供 ClientSecret 或 CertificateName 其中一項。 這些都是獨佔的設定。
實例化 MSAL 應用程式
若要具現化 MSAL 應用程式,請 (視您所使用的程式語言而定) 新增、參考或匯入 MSAL 套件。
取決於您是否使用用戶端密碼、憑證(或者在進階情況下,使用簽名的聲明),結構會有所不同。
參考套件
請在您的應用程式程式碼中參考 MSAL 套件。
將 Microsoft.Identity.Web.TokenAcquisition NuGet 套件新增至應用程式。
或者,如果您想要呼叫 Microsoft Graph,請新增 Microsoft.Identity.Web.GraphServiceClient 套件。
專案可能如下所示。
appsettings.json 檔案必須複製到輸出目錄。
<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>
在 Program.cs 檔案中,在程式碼中新增 using 指示詞以參考 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;
在 npm install 檔案所在的資料夾中執行 package.json,以安裝套件。 接著,匯入 msal-node 套件:
const msal = require('@azure/msal-node');
import msal
import json
import sys
import logging
將 Microsoft.Identity.Client NuGet 套件新增至您的應用程式,然後在程式碼中加入 using 指示詞即可參考該套件。
在 MSAL.NET 中,機密用戶端應用程式會以 IConfidentialClientApplication 介面表示。
using Microsoft.Identity.Client;
IConfidentialClientApplication app;
使用用戶端密碼來具現化機密用戶端應用程式
以下是使用用戶端密碼來具現化機密用戶端應用程式的程式碼:
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();
// ...
}
}
從 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是由雲端執行個體與租用戶識別碼串連而成,例如 https://login.microsoftonline.com/contoso.onmicrosoft.com 或 https://login.microsoftonline.com/aaaabbbb-0000-cccc-1111-dddd2222eeee。 在 [設定檔] 區段內所顯示的 appsettings.json 檔案中,會分別以 Instance 和 Tenant 這兩個值來表示執行個體和租用戶。
在先前程式碼範例中所節錄的程式碼片段中,Authority 是 AuthenticationConfig 類別中的屬性,具有以下的定義:
/// <summary>
/// URL of the authority
/// </summary>
public string Authority
{
get
{
return String.Format(CultureInfo.InvariantCulture, Instance, Tenant);
}
}
使用用戶端憑證來具現化機密用戶端應用程式
以下是建置具有憑證之應用程式的程式碼:
程式碼本身完全相同。 會在設定中描述此憑證。
有許多方式可以取得此憑證。 如需詳細資訊,請參閱 https://aka.ms/ms-id-web-certificates。
以下是從 KeyVault 取得憑證的方式。 Microsoft 身分識別委派給 Azure 身分識別的 DefaultAzureCredential,並在可用時使用託管身分識別從 KeyVault 存取憑證。 您可以在本機對應用程式進行偵錯,因為其會使用開發人員認證。
"ClientCredentials": [
{
"SourceType": "KeyVault",
"KeyVaultUrl": "https://yourKeyVaultUrl.vault.azure.net",
"KeyVaultCertificateName": "NameOfYourCertificate"
}
在 MSAL JAVA 中,有兩個建立器可以具現化具有憑證的機密用戶端應用程式:
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();
或
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);
如需詳細資訊,請參閱將憑證認證用於 MSAL Node.js。
# 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();
進階情境:使用用戶端聲明實例化機密用戶端應用程式
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);
如需詳細資訊,請參閱初始化 ConfidentialClientApplication 物件。
在 MSAL Python 中,您可以使用已由 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
)
如需詳細資訊,請參閱 ConfidentialClientApplication 的 MSAL Python 參考文件。
除了用戶端密碼或憑證外,機密用戶端應用程式還可以使用用戶端判斷提示來證明其身分識別。
MSAL.NET 有兩種方法,可將已簽署的判斷提示提供給機密用戶端應用程式:
.WithClientAssertion()
.WithClientClaims()
當您使用 WithClientAssertion 時,請提供已簽署的 JWT。 本進階案例在用戶端判斷提示中有詳細說明。
string signedClientAssertion = ComputeAssertion();
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithClientAssertion(signedClientAssertion)
.Build();
使用 WithClientClaims 時,MSAL.NET 會產生一個已簽署的斷言,其中包含 Microsoft Entra ID 所需的宣告,以及您想要傳送的其他客戶端宣告。
以下這段程式碼示範了如何進行這項作業:
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();
同樣地,請至客戶端斷言查閱詳細資訊。
下一步