我需要使用 nodejs api 获取一个驱动器中所有文件的列表。我已经在 azure 上注册了一个应用程序,并实现了身份验证的代码流程,如下所述:- OneDrive 身份验证和登录
完成此流程后,我得到如下回复:-
{ token_type: 'Bearer', scope: 'onedrive.readwrite Files.ReadWrite', expires_in: 3600, ext_expires_in: 3600, access_token: 'EwBIA61DBAAUTiVFeGt35mbkQxMI9wgOQmfZjKAAAZOEQOoKIIDONUpQLPCcmj5sM1oecOJkK8...', refresh_token: 'M.C545_BAY.0.U...' }
但是当我尝试使用在上面的响应中收到的访问令牌时,我收到以下错误:-
{ "error": { "code": "InvalidAuthenticationToken", "message": "IDX14100: JWT is not well formed, there are no dots (.).\nThe token needs to be in JWS or JWE Compact Serialization Format. (JWS): 'EncodedHeader.EncodedPayload.EncodedSignature'. (JWE): 'EncodedProtectedHeader.EncodedEncryptedKey.EncodedInitializationVector.EncodedCiphertext.EncodedAuthenticationTag'.", "innerError": { "date": "2024-06-30T13:46:22", "request-id": "2498d892-c5f5-41ee-8883-ac67c3533e46", "client-request-id": "2498d892-c5f5-41ee-8883-ac67c3533e46" } } }
这是我正在尝试的API请求:-
curl --location --request GET 'https://graph.microsoft.com/v2.0/me' \ --header 'Authorization: Bearer EwBIA61DBAAUTiVFeGt35mbkQxMI9wgOQmfZjKAAAZOEQOoKIIDON...'
本论坛的答案表明这是由于访问令牌过期所致。
我尝试使用刷新令牌获取新的访问令牌,但问题并未解决。
注意:根据这个MsDoc,对于个人帐户的OneDrive身份验证和登录,您需要使用Microsoft Graph并仅在Microsoft Graph中对OneDrive进行授权和登录。
创建 Microsoft Entra ID 应用程序并授予 API 权限:
https://login.microsoftonline.com
生成授权码:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
&client_id=ClientID
&response_type=code
&redirect_uri=https://jwt.ms
&response_mode=query
&scope=files.readwrite offline_access
&state=12345
生成代币:
https://login.microsoftonline.com/common/oauth2/v2.0/token
grant_type:authorization_code
client_id:ClientID
client_secret:ClientSecret
scope:files.readwrite offline_access
code:Code
redirect_uri:https://jwt.ms
我用这个token来调用API并且成功了:
curl --location --request GET 'https://graph.microsoft.com/v1.0/me/drive/root/children' \
--header 'Authorization: Bearer EwBYA8l6BAAUbDba3x2OMJElkF7gJ4z/VbCPEz0AAdtv9Wz9KVEmRot'
如果您传递无效的令牌格式或无效的 URL,通常会发生该错误。
要解决该问题,请检查以下内容:
https://graph.microsoft.com/v2.0/me
无效。您需要调用 v1.0 端点,即 https://graph.microsoft.com/v1.0/me
API。要在node.js中执行相同的操作,请使用以下代码并确保传递访问令牌时不带任何空格或额外字符。
const axios = require('axios');
async function listFiles(accessToken) {
const config = {
headers: { Authorization: `Bearer ${accessToken}` }
};
try {
const response = await axios.get('https://graph.microsoft.com/v1.0/me/drive/root/children', config);
console.log(response.data);
} catch (error) {
console.error(error.response ? error.response.data : error.message);
}
}
const accessToken = 'EwBYA8l6BAAUbDba3x2OMJElkF7gJ4z/VbCPEz0AAdtv9Wz9KVEmRo...';
// List files in OneDrive
listFiles(accessToken);
我能够成功调用OneDrive API:
当单词 “Bearer” 与访问令牌一起使用时,我遇到了 同样的错误:
const accessToken = 'Bearer EwBYA8l6BAAUbDba3x2OMJElkF7gJ4z/VbCPEz0AAdtv9Wz9KVEmRo...';