โต้ตอบกับ OneDrive ผ่าน Microsoft Graph API โดยใช้ Access Token

Sep 14 2020

ฉันเป็นมือใหม่ของ Microsoft Graph API และฉันกำลังพยายามเข้าถึง One Drive ผ่าน NodeJS API ฉันได้ทำสิ่งต่อไปนี้เพื่อรับโทเค็นการเข้าถึงจาก Graph 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);
});

ผมทำอะไรผิดหรือเปล่า?

คำตอบ

1 HuryShen Sep 14 2020 at 07:29

คุณต้องใช้ url ดังต่อไปนี้:

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

ระบุรหัสผู้ใช้ใน url เนื่องจากโทเค็นการเข้าถึงของขั้นตอนการให้สิทธิ์ client_credentials ไม่มีตัวตนของผู้ใช้