我正在使用 msal node 最新版本。 这是我的代码:
protected getConfidentialClientApplication(tenantId: string): ConfidentialClientApplication {
if (this.confidentialClientApplication) {
return this.confidentialClientApplication;
}
this.confidentialClientApplication = new ConfidentialClientApplication({
auth: {
clientId: this.tokenConfiguration.clientId,
clientCertificate: {
thumbprint: this.tokenConfiguration.thumbprint,
privateKey: this.tokenConfiguration.privateKey,
x5c: this.tokenConfiguration.publicKey
},
authority: this.tokenConfiguration.authority + tenantId,
knownAuthorities: [this.tokenConfiguration.authority + tenantId]
},
});
return this.confidentialClientApplication;
}
protected getTokenRequest(correlationId: string): ClientCredentialRequest {
return {
scopes: this.getScopes(),
correlationId: correlationId,
azureRegion: "TryAutoDetect"
};
}
我正在调用这个方法:
this.getConfidentialClientApplication(tenantId).acquireTokenByClientCredential(tokenRequest)
如果我正在查看请求的响应,则令牌存在但帐户为空。 另外,
msalTokenCache.getAllAccounts()
;
始终是一个空列表。怎么解决?
根据使用客户端凭据的 Document-msal-authentication-flows
对于客户端凭证流程,您无需用户交互即可获取令牌,重要的是要了解通常不涉及用户帐户。
客户端凭证流程适用于服务器到服务器 通信,不处理用户帐户或用户 互动。
当您使用客户端凭据流程获取令牌时,不会有任何可以使用
检索的缓存帐户。msalTokenCache.getAllAccounts()
以下是如何执行此操作的示例:
const { ConfidentialClientApplication , PublicClientApplication} = require("@azure/msal-node");
const tenantId = "********-****-****-****-***********";
const tokenConfiguration = {
clientId: "********-****-****-****-***********",
clientSecret: "**********************************", // Add your client secret here
authority: "https://login.microsoftonline.com/",
};
const confidentialClientApplication = new ConfidentialClientApplication({
auth: {
clientId: tokenConfiguration.clientId,
clientSecret: tokenConfiguration.clientSecret,
authority: tokenConfiguration.authority + tenantId,
knownAuthorities: [tokenConfiguration.authority + tenantId]
}
});
const tokenRequest = {
scopes: [`${tokenConfiguration.clientId}/.default`], // Replace with the scope you need
azureRegion: "TryAutoDetect"
};
(async () => {
try {
const response = await confidentialClientApplication.acquireTokenByClientCredential(tokenRequest);
console.log("Token response:", response);
const cachedAccounts = await confidentialClientApplication.getTokenCache().getAllAccounts();
console.log("Cached accounts:", cachedAccounts);
} catch (error) {
console.error("Token acquisition error:", error);
}
})();
回复: