![](/img/trans.png)
[英]MS Graph API and DriveItem search not working with client credentials flow
[英]Microsoft Graph API with Simple-OAuth2 and Client Credentials Flow
我正在嘗試使用NodeJS網站中的Simple-OAuth2使用Client Credentials Flow記錄用戶。
我的routes / index.js是這樣的:
var express = require('express');
var router = express.Router();
var authHelper = require('../helpers/auth');
router.get('/', async function(req, res, next) {
let parms = { title: 'Home', active: { home: true } };
const accessToken = await authHelper.accessToken;
res.render('index', parms);
});
module.exports = router;
我的auth.js是這樣的:
const credentials = {
client: {
id: process.env.APP_ID,
secret: process.env.APP_PASSWORD,
},
auth: {
tokenHost: 'https://login.microsoftonline.com',
authorizePath: "common/oauth2/v2.0/authorize",
tokenPath: "common/oauth2/v2.0/token",
}
};
const oauth2 = require('simple-oauth2').create(credentials);
const tokenConfig = {
username: 'uuuuuu@dddddd.com',
password: 'ppppppp',
scope: process.env.APP_SCOPES,
};
try {
const result = await oauth2.ownerPassword.getToken(tokenConfig);
const accessToken = oauth2.accessToken.create(result);
} catch (error) {
console.log('Access Token Error', error.message);
}
exports.accessToken = accessToken;
當我嘗試啟動網站時,nodejs向我顯示了一個sintax錯誤:
const result = await oauth2.ownerPassword.getToken(tokenConfig);
^^^^^
SyntaxError: await is only valid in async function
這個錯誤對我來說沒有多大意義,因為代碼是由simple-oauth2提供的。
有人可以解釋我的實際錯誤嗎?
那么你必須將你的代碼包裝成async
函數,這樣你就可以在該函數中使用await
關鍵字。 你可以在這里找到更多信息。
在你的情況下,我會將代碼包裝到函數中並導出該函數,如下所示:
const credentials = {
client: {
id: process.env.APP_ID,
secret: process.env.APP_PASSWORD,
},
auth: {
tokenHost: 'https://login.microsoftonline.com',
authorizePath: "common/oauth2/v2.0/authorize",
tokenPath: "common/oauth2/v2.0/token",
}
};
const oauth2 = require('simple-oauth2').create(credentials);
const tokenConfig = {
username: 'uuuuuu@dddddd.com',
password: 'ppppppp',
scope: process.env.APP_SCOPES,
};
const getAccessToken = async () => {
try {
const result = await oauth2.ownerPassword.getToken(tokenConfig);
const accessToken = oauth2.accessToken.create(result);
return accessToken;
} catch (error) {
console.log('Access Token Error', error.message);
return null;
}
};
exports.getAccessToken = getAccessToken;
然后你可以使用這樣的功能:
var express = require('express');
var router = express.Router();
var authHelper = require('../helpers/auth');
router.get('/', async function(req, res, next) {
let parms = { title: 'Home', active: { home: true } };
const accessToken = await authHelper.getAccessToken();
res.render('index', parms);
});
module.exports = router;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.