LoginSignup
9
12

More than 5 years have passed since last update.

nodejsでOneDrive APIを使う。主にOAuthとか

Last updated at Posted at 2016-01-07

ざっくりと概要

アプリの登録

https://account.live.com/developers/applications/index
アプリケーションを作成して、
設定>API設定、モバイル クライアント アプリ/デスクトップ クライアント アプリを「はい」に
アプリケーション設定にて表示される、クライアント ID、クライアント シークレットをのちに使用する

認証コードの取得

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

先のクライアントIDを以下のurlに入れて、ブラウザからアクセスする
アドレスバーに/?code=XXXXXXと、認証コードが含まれるので、これをアプリの中で使う。この操作は最初の1回でよい

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

アクセストークンの要求

認証コードを使い、リフレッシュトークンを取得する

JavaScript
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を使用するときはheaderにアクセストークンを含める
アクセストークンはexpires_inプロパティで指定された秒数だけ有効なので、この操作は毎回行うことになる。そのため、リフレッシュトークンを保存しておき、次回使うときは保存したリフレッシュトークンでアクセストークンを取得する

JavaScript
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の使用例

JavaScript
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){
    ・・・
    ・・・
});
9
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
12