適用於:綠色圓圈加上白色複選標記符號的
員工租戶
外部租戶(了解更多)
在本教學課程中,您會從 Node/Express.js Web 應用程式呼叫 Microsoft Graph API。 使用者登入之後,應用程式會取得存取令牌,以呼叫 Microsoft Graph API。
本教學課程是 3 部分教學課程系列的第 3 部分。
在本教學課程中,您會:
- 更新 Node/Express.js Web 應用程式以取得存取令牌
- 使用存取令牌來呼叫 Microsoft Graph API。
先決條件
- 完成在 教學課程中:使用 Microsoft 身分識別平臺,將登入功能新增至 Node/Express.js Web 應用程式的步驟。
新增UI元件
在您的程式代碼編輯器中,開啟 views/index.hbs 檔案,然後使用下列代碼段新增 檢視使用者配置檔 連結:
<a href="/users/profile">View user profile</a>進行更新之後,views/index.hbs 檔案看起來應該類似下列檔案:
<h1>{{title}}</h1> {{#if isAuthenticated }} <p>Hi {{username}}!</p> <a href="/users/id">View ID token claims</a> <br> <a href="/users/profile">View user profile</a> <br> <br> <a href="/auth/signout">Sign out</a> {{else}} <p>Welcome to {{title}}</p> <a href="/auth/signin">Sign in</a> {{/if}}建立 views/profile.hbs 檔案,然後新增下列程序代碼:
<h1>Microsoft Graph API</h1> <h3>/me endpoint response</h3> <table> <tbody> {{#each profile}} <tr> <td>{{@key}}</td> <td>{{this}}</td> </tr> {{/each}} </tbody> </table> <br> <a href="/">Go back</a>- 此頁面會顯示Microsoft Graph API 傳回的使用者配置檔詳細數據。
取得存取令牌
在您的程式代碼編輯器中,開啟 驗證/AuthProvider.js 檔案,然後在 getToken 類別中新增 AuthProvider 方法:
class AuthProvider {
//...
getToken(scopes, redirectUri = "http://localhost:3000/") {
return async function (req, res, next) {
const msalInstance = authProvider.getMsalInstance(authProvider.config.msalConfig);
try {
msalInstance.getTokenCache().deserialize(req.session.tokenCache);
const silentRequest = {
account: req.session.account,
scopes: scopes,
};
const tokenResponse = await msalInstance.acquireTokenSilent(silentRequest);
req.session.tokenCache = msalInstance.getTokenCache().serialize();
req.session.accessToken = tokenResponse.accessToken;
next();
} catch (error) {
if (error instanceof msal.InteractionRequiredAuthError) {
req.session.csrfToken = authProvider.cryptoProvider.createNewGuid();
const state = authProvider.cryptoProvider.base64Encode(
JSON.stringify({
redirectTo: redirectUri,
csrfToken: req.session.csrfToken,
})
);
const authCodeUrlRequestParams = {
state: state,
scopes: scopes,
};
const authCodeRequestParams = {
state: state,
scopes: scopes,
};
authProvider.redirectToAuthCodeUrl(
req,
res,
next,
authCodeUrlRequestParams,
authCodeRequestParams,
msalInstance
);
}
next(error);
}
};
}
}
//...
getToken 方法會使用指定的範圍來取得存取令牌
新增呼叫 API 路由
在您的程式代碼編輯器中,開啟 routes/users.js 檔案,然後新增下列路由:
router.get(
"/profile",
isAuthenticated,
authProvider.getToken(["User.Read"]), // check if user is authenticated
async function (req, res, next) {
const graphResponse = await fetch(
GRAPH_ME_ENDPOINT,
req.session.accessToken,
);
if (!graphResponse.id) {
return res
.status(501)
.send("Failed to fetch profile details");
}
res.render("profile", {
profile: graphResponse,
});
},
);
當客戶用戶選取
/profile連結時,就會觸發 路由。 應用程式:- 取得具有 User.Read 許可權的存取令牌。
- 呼叫 Microsoft Graph API 以讀取已登入使用者的配置檔。
- 在 profile.hbs UI 中顯示使用者詳細數據。
呼叫 Microsoft Graph API
建立 fetch.js 檔案,然後新增下列程序代碼:
var axios = require('axios');
var authProvider = require("./auth/AuthProvider");
/**
* Makes an Authorization "Bearer" request with the given accessToken to the given endpoint.
* @param endpoint
* @param accessToken
* @param method
*/
const fetch = async (endpoint, accessToken, method = "GET", data = null) => {
const options = {
headers: {
Authorization: `Bearer ${accessToken}`,
},
};
console.log(`request made to ${endpoint} at: ` + new Date().toString());
try{
const response = await axios.get(endpoint, options);
return await response.data;
}catch(error){
throw new Error(error);
}
};
module.exports = { fetch };
實際的 API 呼叫會在 fetch.js 檔案中發生。
執行及測試 Node/Express.js Web 應用程式
- 使用 執行和測試 Node/Express.js Web 應用程式中的步驟, 執行您的 Web 應用程式。
- 登入之後,請選取 檢視使用者配置檔 連結。 如果您的應用程式正常運作,您應該會看到已登入使用者的個人資料,這些資料是從 Microsoft Graph API 讀取的。