调用 Web API 的 Web 应用:获取应用的令牌

你已构建了客户端应用程序对象。 现在,你使用它获取令牌来调用 Web API。 在 ASP.NET 或 ASP.NET Core 中,调用 Web API 是在控制器中完成的。

  • 使用令牌缓存获取 Web API 的令牌。 若要获取此令牌,请调用 Microsoft 身份验证库 (MSAL) AcquireTokenSilent 方法(或 Microsoft.Identity.Web 中的等效方法)。
  • 调用受保护的 API,将访问令牌作为参数传递给它。

在 Java 示例中,调用 API 的代码位于 AuthPageController.java#L62 中的 getUsersFromGraph 方法中。

该方法尝试调用 getAuthResultBySilentFlow。 如果用户需要许可更多作用域,则该代码会处理 MsalInteractionRequiredException 对象来质询用户。

@RequestMapping("/msal4jsample/graph/me")
public ModelAndView getUserFromGraph(HttpServletRequest httpRequest, HttpServletResponse response)
        throws Throwable {

    IAuthenticationResult result;
    ModelAndView mav;
    try {
        result = authHelper.getAuthResultBySilentFlow(httpRequest, response);
    } catch (ExecutionException e) {
        if (e.getCause() instanceof MsalInteractionRequiredException) {

            // If the silent call returns MsalInteractionRequired, redirect to authorization endpoint
            // so user can consent to new scopes.
            String state = UUID.randomUUID().toString();
            String nonce = UUID.randomUUID().toString();

            SessionManagementHelper.storeStateAndNonceInSession(httpRequest.getSession(), state, nonce);

            String authorizationCodeUrl = authHelper.getAuthorizationCodeUrl(
                    httpRequest.getParameter("claims"),
                    "https://microsoftgraph.chinacloudapi.cn/user.read",
                    authHelper.getRedirectUriGraph(),
                    state,
                    nonce);

            return new ModelAndView("redirect:" + authorizationCodeUrl);
        } else {

            mav = new ModelAndView("error");
            mav.addObject("error", e);
            return mav;
        }
    }

    if (result == null) {
        mav = new ModelAndView("error");
        mav.addObject("error", new Exception("AuthenticationResult not found in session."));
    } else {
        mav = new ModelAndView("auth_page");
        setAccountInfo(mav, httpRequest);

        try {
            mav.addObject("userInfo", getUserInfoFromGraph(result.accessToken()));

            return mav;
        } catch (Exception e) {
            mav = new ModelAndView("error");
            mav.addObject("error", e);
        }
    }
    return mav;
}
// Code omitted here

后续步骤

转到此方案中的下一篇文章:调用 Web API