Microsoft Graph for Office 365 - 用例:在单页应用程序中调用Microsoft Graph Part 2

经过上一篇的介绍之后,今天我们将演示使用MSAL(微软认证库)实现在单页应用程序中对Microsoft Graph的调用操作。
Microsoft Graph for Office 365 - 用例:在单页应用程序中调用Microsoft Graph Part 2_第1张图片

配置代码示例

我们需要安装Node,这样才能编译TypeScript。
首先,从https://github.com/BobGerman/AADsamples下载代码示例,我们要演示的内容在implicitFlow文件夹。
打开命令行工具,进入到implicitFlow目录,依次执行如下命令:

npm install
npm install http-server -g

等待执行完成后,打开文件index.2a.html,将替换为我们自己的Client ID。
Microsoft Graph for Office 365 - 用例:在单页应用程序中调用Microsoft Graph Part 2_第2张图片
将src文件夹中的constants.sample.ts重命名为constants.ts,将里面的clientIdV2同样设置为我们自己的Client ID。
Microsoft Graph for Office 365 - 用例:在单页应用程序中调用Microsoft Graph Part 2_第3张图片
这样就可以了,执行命令npm run build进行编译。

运行代码示例

执行命令http-server
Microsoft Graph for Office 365 - 用例:在单页应用程序中调用Microsoft Graph Part 2_第4张图片
如图就是运行起来了,现在我们可以打开浏览器访问地址http://localhost:8080/index.html了。点击V2 endpoint (Javascript)和V2 endpoint (Typescript)。登录之后即可查看到相应内容。
Microsoft Graph for Office 365 - 用例:在单页应用程序中调用Microsoft Graph Part 2_第5张图片
Microsoft Graph for Office 365 - 用例:在单页应用程序中调用Microsoft Graph Part 2_第6张图片

代码解析

这部分我们来看一下核心的一些代码是如何实现的。

JavaScript示例
index.2a.html - V2 endpoint (Javascript)
页面上有一个按钮用来登录和注销,当访问这个页面时,会判断是不是已登录状态,如果没有登录则显示Sign In供用户登录,登录的代码如下:

function signIn() {
    myMSALObj.loginPopup(applicationConfig.graphScopes).then(function (idToken) {
        //Login Success
        showWelcomeMessage();
        acquireTokenPopupAndCallMSGraph();
    }, function (error) {
        console.log(error);
    });
}

这段代码用于弹出登录窗口并取回用户登录成功后的token。

TypeScript示例
index.2b.html - V2 endpoint (Typescript)
示例代码中包含了两个TypeScript服务,MSGraphService(用于调用Graph)和AuthService(用于获取token)。
MSGraphService不需要关心认证问题,而只需要在访问时索要token以发起请求,大致代码结构如下。

this.authService.getToken()
    .then((token) => {
        fetch(
            `https://graph.microsoft.com/v1.0/groups/?$orderby=displayName`,
            {
                method: "GET",
                mode: "cors",
                cache: "no-cache",
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": "Bearer " + token
                }
            }
        )
        .then((response) => {
            // handle the response
        }
        // ...

然后,使用Msal.UserAgentApplication获取用户token。

// Ensure user is logged in
if (!userAgentApp.getUser() || userAgentApp.isCallback(window.location.hash)) {
    userAgentApp.loginRedirect(constants.scopes);
}

// Try to get a token silently
userAgentApp.acquireTokenSilent(constants.scopes)
    .then((accessToken) => {
        resolve(accessToken);
    })
    .catch((error) => {
        console.log(error);
        // If the error is due to a need for user interaction, then redirect to allow it
        if (error.indexOf("consent_required") !== -1 ||error.indexOf("interaction_required") !== -1 || error.indexOf("login_required") !== -1) {
            userAgentApp.acquireTokenRedirect(constants.scopes);
        } else {
            reject('Error acquiring token: ' + error);
        }
    });

希望这两篇能对想要调用Graph的Web开发者们提供帮助。

你可能感兴趣的:(Microsoft,365,Microsoft,Graph,Microsoft,Graph,30天训练营中文版)