使用访问令牌通过 Microsoft Graph API 与 OneDrive 交互

Interact with OneDrive through Microsoft Graph API using Access Token

我是 Microsoft Graph API 的新手,我正在尝试通过 NodeJS API 访问 One Drive。我已完成以下操作以从图表中获取访问令牌 API 以便访问我的 One Drive 而无需用户每次想要访问我的驱动器上的内容时都必须登录。

const postData = {
  client_id: 'xxxxxxxxxxxxxxxxxxx',
  scope: 'https://graph.microsoft.com/.default',
  client_secret: 'xxxxxxxxxxxxxxxxxxx',
  grant_type: 'client_credentials'
};

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// Get  access token and assign it to the token variable
axios
  .post('https://login.microsoftonline.com/xxxxxxxxxxxxxxxxxxx/oauth2/v2.0/token', qs.stringify(postData))
  .then(response => {
    token = response.data.access_token;
  }).catch(error => {
    console.log(error);
  });

我的 API 正在成功获取令牌。但是,当我尝试使用此令牌和文档中提供的端点访问我的 One Drive 时出现错误。代码如下:

const AuthStr = 'Bearer ' + token;

axios.get('https://graph.microsoft.com/v1.0/drive/root/children', { headers: { Authorization: AuthStr } }).then(response => {
    console.log(response);
}).catch((error) => {
    console.log(error);
});

我做错了什么?

您只需要使用 url 如下:

https://graph.microsoft.com/v1.0/users/{userid}/drive/root/children

在 url 中指定用户 ID,因为 client_credentials 授权流程的访问令牌不包含用户身份。