生成公共客户端应用程序的实例后,你将使用它来获取一个令牌,然后使用该令牌调用 Web API。
推荐的模式
Web API 由其 scopes 定义。 无论在应用程序中提供哪种体验,要使用的模式都是:
- 通过调用
AcquireTokenSilent
系统性地尝试从令牌缓存中获取令牌。
- 如果此调用失败,则使用所需的
AcquireToken
流(此处由 AcquireTokenXX
表示)。
在 MSAL.NET 中
AuthenticationResult result;
var accounts = await app.GetAccountsAsync();
IAccount account = ChooseAccount(accounts); // for instance accounts.FirstOrDefault
// if the app manages is at most one account
try
{
result = await app.AcquireTokenSilent(scopes, account)
.ExecuteAsync();
}
catch(MsalUiRequiredException ex)
{
result = await app.AcquireTokenXX(scopes, account)
.WithOptionalParameterXXX(parameter)
.ExecuteAsync();
}
Set<IAccount> accountsInCache = pca.getAccounts().join();
// Take first account in the cache. In a production application, you would filter
// accountsInCache to get the right account for the user authenticating.
IAccount account = accountsInCache.iterator().next();
IAuthenticationResult result;
try {
SilentParameters silentParameters =
SilentParameters
.builder(SCOPE, account)
.build();
// try to acquire token silently. This call will fail since the token cache
// does not have any data for the user you are trying to acquire a token for
result = pca.acquireTokenSilently(silentParameters).join();
} catch (Exception ex) {
if (ex.getCause() instanceof MsalException) {
InteractiveRequestParameters parameters = InteractiveRequestParameters
.builder(new URI("http://localhost"))
.scopes(SCOPE)
.build();
// Try to acquire a token interactively with system browser. If successful, you should see
// the token and account information printed out to console
result = pca.acquireToken(parameters).join();
} else {
// Handle other exceptions accordingly
throw ex;
}
}
return result;
在适用于 iOS 和 macOS 的 MSAL 中
Objective-C:
MSALAccount *account = [application accountForIdentifier:accountIdentifier error:nil];
MSALSilentTokenParameters *silentParams = [[MSALSilentTokenParameters alloc] initWithScopes:scopes account:account];
[application acquireTokenSilentWithParameters:silentParams completionBlock:^(MSALResult *result, NSError *error) {
// Check the error
if (error && [error.domain isEqual:MSALErrorDomain] && error.code == MSALErrorInteractionRequired)
{
// Interactive auth will be required, call acquireTokenWithParameters:error:
}
}];
Swift:
guard let account = try? application.account(forIdentifier: accountIdentifier) else { return }
let silentParameters = MSALSilentTokenParameters(scopes: scopes, account: account)
application.acquireTokenSilent(with: silentParameters) { (result, error) in
guard let authResult = result, error == nil else {
let nsError = error! as NSError
if (nsError.domain == MSALErrorDomain &&
nsError.code == MSALError.interactionRequired.rawValue) {
// Interactive auth will be required, call acquireToken()
return
}
return
}
}
在 MSAL 节点中,可以使用代码交换证明密钥 (PKCE) 通过授权代码流获取令牌。 MSAL 节点使用内存中令牌缓存来查看缓存中是否有任何用户帐户。 如果有,则可以将帐户对象传递到 acquireTokenSilent()
方法以检索缓存的访问令牌。
const msal = require("@azure/msal-node");
const msalConfig = {
auth: {
clientId: "your_client_id_here",
authority: "your_authority_here",
}
};
const pca = new msal.PublicClientApplication(msalConfig);
const msalTokenCache = pca.getTokenCache();
let accounts = await msalTokenCache.getAllAccounts();
if (accounts.length > 0) {
const silentRequest = {
account: accounts[0], // Index must match the account that is trying to acquire token silently
scopes: ["https://microsoftgraph.chinacloudapi.cn/user.read"],
};
pca.acquireTokenSilent(silentRequest).then((response) => {
console.log("\nSuccessful silent token acquisition");
console.log("\nResponse: \n:", response);
res.sendStatus(200);
}).catch((error) => console.log(error));
} else {
const {verifier, challenge} = await msal.cryptoProvider.generatePkceCodes();
const authCodeUrlParameters = {
scopes: ["https://microsoftgraph.chinacloudapi.cn/user.read"],
redirectUri: "your_redirect_uri",
codeChallenge: challenge, // PKCE Code Challenge
codeChallengeMethod: "S256" // PKCE Code Challenge Method
};
// get url to sign user in and consent to scopes needed for application
pca.getAuthCodeUrl(authCodeUrlParameters).then((response) => {
console.log(response);
const tokenRequest = {
code: response["authorization_code"],
codeVerifier: verifier, // PKCE Code Verifier
redirectUri: "your_redirect_uri",
scopes: ["https://microsoftgraph.chinacloudapi.cn/user.read"],
};
// acquire a token by exchanging the code
pca.acquireTokenByCode(tokenRequest).then((response) => {
console.log("\nResponse: \n:", response);
}).catch((error) => {
console.log(error);
});
}).catch((error) => console.log(JSON.stringify(error)));
}
result = None
# Firstly, check the cache to see if this end user has signed in before
accounts = app.get_accounts(username=config["username"])
if accounts:
result = app.acquire_token_silent(config["scope"], account=accounts[0])
if not result:
result = app.acquire_token_by_xxx(scopes=config["scope"])
可以通过多种方式在桌面应用程序中获取令牌。
如果用户需使用多重身份验证 (MFA) 来登录应用程序,则系统会改为阻止用户。
后续步骤
转到此方案中的下一篇文章:从桌面应用调用 Web API。