单页应用程序:获取用于调用 API 的令牌Single-page application: Acquire a token to call an API

使用 MSAL.js 获取 API 的令牌时,其模式是首先使用 acquireTokenSilent 方法来尝试无提示令牌请求。The pattern for acquiring tokens for APIs with MSAL.js is to first attempt a silent token request by using the acquireTokenSilent method. 调用此方法时,该库会首先检查浏览器存储中的缓存,看是否存在有效的令牌,在有的情况下会将其返回。When this method is called, the library first checks the cache in browser storage to see if a valid token exists and returns it. 如果缓存中没有有效的令牌,则会从隐藏的 iframe 向 Azure Active Directory (Azure AD) 发送一个无提示令牌请求。When no valid token is in the cache, it sends a silent token request to Azure Active Directory (Azure AD) from a hidden iframe. 库也可以通过此方法来续订令牌。This method also allows the library to renew tokens.

可能会因某些原因(例如 Azure AD 会话过期,或者密码已更改)而导致以无提示方式向 Azure AD 请求令牌失败。The silent token requests to Azure AD might fail for reasons like an expired Azure AD session or a password change. 在这种情况下,可以调用某个交互方法(会提示用户)来获取令牌:In that case, you can invoke one of the interactive methods (which will prompt the user) to acquire tokens:

在弹出窗口或重定向体验之间进行选择Choose between a pop-up or redirect experience

不能在应用程序中同时使用弹出窗口和重定向方法。You can't use both the pop-up and redirect methods in your application. 在弹出窗口和重定向体验之间进行的选择取决于应用程序流:The choice between a pop-up or redirect experience depends on your application flow:

  • 如果不希望用户在身份验证期间离开主应用程序页,建议使用弹出窗口方法。If you don't want users to move away from your main application page during authentication, we recommended the pop-up method. 由于身份验证重定向发生在弹出窗口中,系统会保留主应用程序的状态。Because the authentication redirect happens in a pop-up window, the state of the main application is preserved.

  • 如果用户的浏览器约束或策略禁用了弹出窗口,则可使用重定向方法。If users have browser constraints or policies where pop-ups windows are disabled, you can use the redirect method. 请对 Internet Explorer 浏览器使用重定向方法,因为 Internet Explorer 上具有弹出窗口的已知问题Use the redirect method with the Internet Explorer browser, because there are known issues with pop-up windows on Internet Explorer.

可以设置 API 作用域,在生成访问令牌请求时需要访问令牌包括这些作用域。You can set the API scopes that you want the access token to include when it's building the access token request. 请注意,可能不会在访问令牌中授予所有请求的作用域。Note that all requested scopes might not be granted in the access token. 具体取决于用户的许可。That depends on the user's consent.

通过弹出窗口获取令牌Acquire a token with a pop-up window

以下代码将前面描述的模式与弹出体验的方法结合起来:The following code combines the previously described pattern with the methods for a pop-up experience:

const accessTokenRequest = {
    scopes: ["https://microsoftgraph.chinacloudapi.cn/user.read"]
}

userAgentApplication.acquireTokenSilent(accessTokenRequest).then(function(accessTokenResponse) {
    // Acquire token silent success
    // Call API with token
    let accessToken = accessTokenResponse.accessToken;
}).catch(function (error) {
    //Acquire token silent failure, and send an interactive request
    if (error.errorMessage.indexOf("interaction_required") !== -1) {
        userAgentApplication.acquireTokenPopup(accessTokenRequest).then(function(accessTokenResponse) {
            // Acquire token interactive success
        }).catch(function(error) {
            // Acquire token interactive failure
            console.log(error);
        });
    }
    console.log(error);
});

通过重定向获取令牌Acquire a token with a redirect

以下模式如前文所述,但显示的是如何使用重定向方法以交互方式获取令牌。The following pattern is as described earlier but shown with a redirect method to acquire tokens interactively. 你需注册重定向回叫,如前文所述。You'll need to register the redirect callback as mentioned earlier.

function authCallback(error, response) {
    // Handle redirect response
}

userAgentApplication.handleRedirectCallback(authCallback);

const accessTokenRequest: AuthenticationParameters = {
    scopes: ["https://microsoftgraph.chinacloudapi.cn/user.read"]
}

userAgentApplication.acquireTokenSilent(accessTokenRequest).then(function(accessTokenResponse) {
    // Acquire token silent success
    // Call API with token
    let accessToken = accessTokenResponse.accessToken;
}).catch(function (error) {
    //Acquire token silent failure, and send an interactive request
    console.log(error);
    if (error.errorMessage.indexOf("interaction_required") !== -1) {
        userAgentApplication.acquireTokenRedirect(accessTokenRequest);
    }
});

请求可选声明Request optional claims

可以使用可选声明来实现以下目的:You can use optional claims for the following purposes:

  • 在应用程序的令牌中包括其他声明。Include additional claims in tokens for your application.
  • 更改 Azure AD 在令牌中返回的某些声明的行为。Change the behavior of certain claims that Azure AD returns in tokens.
  • 添加和访问应用程序的自定义声明。Add and access custom claims for your application.

若要请求 IdToken 中的可选声明,可以将一个字符串化声明对象发送到 AuthenticationParameters.ts 类的 claimsRequest 字段。To request optional claims in IdToken, you can send a stringified claims object to the claimsRequest field of the AuthenticationParameters.ts class.

"optionalClaims":
   {
      "idToken": [
            {
                  "name": "auth_time",
                  "essential": true
             }
      ],

var request = {
    scopes: ["https://microsoftgraph.chinacloudapi.cn/user.read"],
    claimsRequest: JSON.stringify(claims)
};

myMSALObj.acquireTokenPopup(request);

如需了解详细信息,请参阅可选声明To learn more, see Optional claims.

后续步骤Next steps