使用Node.js来操作OneDrive API。主要涉及OAuth等技术

大致概述

APP注册

创建应用程序后,在”设置> API设置”中的”移动客户端应用程序/桌面客户端应用程序”中选择”是”。
稍后在应用程序设置中显示的客户端ID和客户端秘钥将用于后续使用。

获取认证码

请参考 https://msdn.microsoft.com/ja-jp/library/hh243647.aspx

将先前的客户端ID放入以下网址中,从浏览器访问。
在地址栏中输入/?code=XXXXXX,其中包含了认证码,将在应用程序中使用此认证码。此操作只需要在最初进行一次即可。

https://login.live.com/oauth20_authorize.srf?client_id=クライアントID&scope=wl.signin onedrive.readwrite wl.offline_access&response_type=code

请求访问令牌

使用验证代码以获取刷新令牌

var url = 'https://login.live.com/oauth20_token.srf';

request.post({
    url: url,
    form: {
        client_id: client_id,
        client_secret: client_secret,
        code: /* 認証コード */,
        grant_type: 'authorization_code'
    },
    json: true,
    headers: {  'Content-Type': 'application/x-www-form-urlencoded' }
}, function(error, response, d){
    if (!error && response.statusCode == 200)
        console.log(d.refresh_token);   // リフレッシュトークンの取得
    else
        console.log(response);
});

更新访问令牌

使用刷新令牌来更新访问令牌
以后在使用API时,需包含访问令牌在头部
访问令牌只在expires_in属性指定的秒数内有效,因此需要每次都执行此操作。因此,将刷新令牌保存下来,在下次使用时使用保存的刷新令牌获取访问令牌。

var url = 'https://login.live.com/oauth20_token.srf';

request.post({
    url: url,
    form: {
        client_id: client_id,
        client_secret: client_secret,
        refresh_token: /* リフレッシュトークン */,
        grant_type: 'refresh_token'
    },
    json: true,
    headers: {  'Content-Type': 'application/x-www-form-urlencoded' }
}, function(error, response, d){
    if (!error && response.statusCode == 200) {
        //  リフレッシュトークンの保存
        fs.writeFileSync('refresh_token.txt', d.refresh_token);

        //アクセストークン
        console.log(d.access_token);
    } else {
        console.log(response);
    }
});

API的使用示例

var root = 'https://api.onedrive.com/v1.0';
var refresh_token = fs.readFileSync('refresh_token.txt', 'utf-8');

//  アクセストークン更新
//  var ACCESS_TOKEN = 

request.get({
    url: root+'/drive/items/ディレクトリのIDとか/children',
    headers: {
        Authorization: 'Bearer ' + ACCESS_TOKEN
    },
    json: true,
}, function(error, response, d){
    ・・・
    ・・・
});
广告
将在 10 秒后关闭
bannerAds