我正在尝试通过 API 访问 onedrive。我已经成功获得了具有 files.readwrite 范围的 acces_token 。当我尝试访问https://graph.microsoft.com/v1.0/me时。它响应错误“InvalidAuthenticationToken”。我做错了什么
我尝试了一堆不同的网址,例如“https://graph.microsoft.com/v1.0/me/drive/root/children ”并搜索了 stackoverflow,但没有任何帮助。
router.get('/response', function(req, res, next){
// already got code here.
var code = req.query.code
request.post({
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
headers: { 'Content-Type': 'application/x-www-form-urlencoded'},
form: {
client_id: client_id,
redirect_uri: redirect_uri,
client_secret: client_secret,
code: code,
grant_type: 'authorization_code',
},
},function(error, response, body){
if (error){
console.log(error)
}
//so far so good. The access_token from the response looks okay and the
//scope is correct as well
request.get({
url: 'https://graph.microsoft.com/v1.0/me',
headers: {
'Authorization': "Bearer " + JSON.parse(body).access_token,
},
}, function(er, re, bo) {
//this response is an error message
console.log(bo)
});
});
})
我希望收到包含有关 onedrive 的信息的请求,但收到一条错误消息。
最佳答案
您的身份验证流程尚未完成,您返回的代码是身份验证代码,而不是 token 。这是一个非常重要的区别。
oAuth 代码流程的第一步是获取代码,正如您所做的那样。然后您需要将此代码“交易”为实际的代币。为此,您需要使用此代码向服务器发送另一个请求并请求您的 token 。此请求应转到不同的 URL。对于您现在使用的流程,这里有很多深入的解释 https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
这里是隐式流程,如果您打算使用它:https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow
您可能还想考虑使用 AdalJS 或预览版 MSAL.js 库来为您处理大量身份验证工作,这些是 Microsoft 制作的库。
关于node.js - 我获得了 microsoft graph 的身份验证代码,但是当我尝试使用它时,响应是 InvalidAuthenticationToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55690913/