这个问题建立在 How to get Microsoft Graph API Access token from Node Script? 的基础上但是,作为首次用户,我没有必要的声誉来评论该线程中已接受的答案。
问题是,我尝试实现已接受答案建议的方法,但在某个地方出了问题。下面的代码是异步函数的一部分,我已经可以告诉您ONEDRIVE_TENANT_URI
的格式为XXX.onmicrosoft.com
。
const endpoint = `https://login.microsoftonline.com/${process.env.ONEDRIVE_TENTANT_URI}/oauth2/token`;
const requestParams = {
grant_type: "client_credentials",
client_id: process.env.ONEDRIVE_APP_ID,
client_secret: process.env.ONEDRIVE_CLIENT_SECRET,
resource: "https://graph.windows.net"
};
const authResponse = await request.post({
url: endpoint,
form: requestParams
});
authResponse
获取一个字符串作为其正文,其中填写了上面定义的 requestParams。
如果我通过 Postman 提交 post 请求,并使用与 x-www-form-urlencoded 相同的参数,我确实会在响应正文中获得一个 access_token
。
所以...我做错了什么?也许 - 但我不这么认为 - 这是因为这个函数是由(出于测试目的)带有 json 格式主体的 POSTMAN GET 请求调用的?
最佳答案
您可以下载示例here 。并在 config.js 中填写凭据。您可以从 Azure 门户找到它们。
这是获取访问 token 的代码。
auth.getAccessToken = function () {
var deferred = Q.defer();
// These are the parameters necessary for the OAuth 2.0 Client Credentials Grant Flow.
// For more information, see Service to Service Calls Using Client Credentials (https://msdn.microsoft.com/library/azure/dn645543.aspx).
var requestParams = {
grant_type: 'client_credentials',
client_id: config.clientId,
client_secret: config.clientSecret,
resource: 'https://graph.microsoft.com'
};
// Make a request to the token issuing endpoint.
request.post({ url: config.tokenEndpoint, form: requestParams }, function (err, response, body) {
var parsedBody = JSON.parse(body);
console.log(parsedBody);
if (err) {
deferred.reject(err);
} else if (parsedBody.error) {
deferred.reject(parsedBody.error_description);
} else {
// If successful, return the access token.
deferred.resolve(parsedBody.access_token);
}
});
return deferred.promise;
};
关于node.js - 从 Nodejs 脚本获取 Microsoft GRAPH 访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55167866/