5

After a time I finally figure out how to use oAuth2 and how to create a access token with the refresh token. But I can´t find node.js samples for upload files the only thing I found was this module https://www.npmjs.com/package/onedrive-api

But this didn´t work for me because I get this error { error: { code: 'unauthenticated', message: 'Authentication failed' } }

Also if I would enter accessToken: manually with 'xxxxxxx' the result would be the same.

But I created before the upload the access token so I don´t know if this really can be a invalid credits problem. But the funny thing is if I would take the access token from https://dev.onedrive.com/auth/msa_oauth.htm where you can generate a 1h access token the upload function works. I created my auth with the awnser from this question. OneDrive Code Flow Public clients can't send a client secret - Node.js
Also I only used the scope Files.readWrite.all do I maybe need to allow some other scopes ? My code is

const oneDriveAPI = require('onedrive-api');
const onedrive_json_configFile = fs.readFileSync('./config/onedrive.json', 'utf8');
const onedrive_json_config = JSON.parse(onedrive_json_configFile);
const onedrive_refresh_token = onedrive_json_config.refresh_token
const onedrive_client_secret = onedrive_json_config.client_secret
const onedrive_client_id = onedrive_json_config.client_id






// use the refresh token to create access token
request.post({
    url:'https://login.microsoftonline.com/common/oauth2/v2.0/token',
    form: {
        redirect_uri: 'http://localhost/dashboard',
        client_id: onedrive_client_id,
        client_secret: onedrive_client_secret,
        refresh_token: onedrive_refresh_token,
        grant_type: 'refresh_token'
    }
}, function(err,httpResponse,body){
if (err) {
console.log('err: ' + err)
}else{
console.log('body full: ' + body)
var temp = body.toString()
temp = temp.match(/["]access[_]token["][:]["](.*?)["]/gmi)
//console.log('temp1: ', temp)
temp = temp.join("")
temp = temp.replace('"access_token":"','')
temp = temp.replace('"','')
temp = temp.replace('\n','')
temp = temp.replace('\r','')
//console.log('temp4: ', temp)



oneDriveAPI.items.uploadSimple({
  accessToken: temp,
  filename: 'box.zip',
  parentPath: 'test',
  readableStream: fs.createReadStream('C:\\Exports\\box.zip')
})
.then((item,body) => {
console.log('item file upload OneDrive: ', item); 
console.log('body file upload OneDrive: ', body); 
// returns body of https://dev.onedrive.com/items/upload_put.htm#response 
})
.catch((err) => {
console.log('Error while uploading File to OneDrive: ', err); 
});



} // else from if (err) { from request.post
}); // request.post({ get access token with refresh token

Can you send me your sample codes please to upload a file to OneDrive API with node.js. Would be great. Thank you

Edit: I also tried to upload a file with this

  var uri = 'https://api.onedrive.com/v1.0/drive/root:/' + 'C:/files/file.zip' + ':/content'

  var options = {
      method: 'PUT',
      uri: uri,
      headers: {
        Authorization: "Bearer " + accesstoken
      },
      json: true
    };

request(options, function (err, res, body){

if (err) {
console.log('#4224 err:', err)
}
console.log('#4224 body:', body)

});

Same code: 'unauthenticated' stuff :/

t33n
  • 270
  • 1
  • 3
  • 17

1 Answers1

13

How about this sample script? The flow of this sample is as follows.

  1. Retrieve access token using refresh token.
  2. Upload a file using access token.

When you use this sample, please import filename, your client id, client secret and refresh token. The detail information is https://dev.onedrive.com/items/upload_put.htm.

Sample script :

var fs = require('fs');
var mime = require('mime');
var request = require('request');

var file = 'c:/Exports/box.zip'; // Filename you want to upload on your local PC
var onedrive_folder = 'samplefolder'; // Folder name on OneDrive
var onedrive_filename = 'box.zip'; // Filename on OneDrive

request.post({
    url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
    form: {
        redirect_uri: 'http://localhost/dashboard',
        client_id: onedrive_client_id,
        client_secret: onedrive_client_secret,
        refresh_token: onedrive_refresh_token,
        grant_type: 'refresh_token'
    },
}, function(error, response, body) {
    fs.readFile(file, function read(e, f) {
        request.put({
            url: 'https://graph.microsoft.com/v1.0/drive/root:/' + onedrive_folder + '/' + onedrive_filename + ':/content',
            headers: {
                'Authorization': "Bearer " + JSON.parse(body).access_token,
                'Content-Type': mime.lookup(file),
            },
            body: f,
        }, function(er, re, bo) {
            console.log(bo);
        });
    });
});

If I misunderstand your question, I'm sorry.

Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • 1
    You saved my day again. thank you sooooo much <3. Also I think they only thing that was missing was Content-Type. Because in the unofficial onedrive npmjs module I post on the top, they also didn´t include Content-Type. – t33n Aug 14 '17 at 15:37
  • Hey sadly your code only works for files under 4MB. Do you have working sample codes for uploadsession? I got new questions related to this here https://stackoverflow.com/questions/45684079/onedrive-api-node-js-can%C2%B4t-use-createuploadsession-content-range-error – t33n Aug 14 '17 at 22:43
  • @t33n Welcome. Thank you, too. I try to think about uploading large size file. – Tanaike Aug 14 '17 at 23:06
  • @Tanaike: Sorry for the silly question: How can I get `refresh_token`? I can't find this in Azure app. In Azure app, I can see `client_id` and `client_secret`. – Saurabh Chauhan Jul 01 '20 at 12:43
  • @Saurabh Chauhan Thank you for your comment. This question is not your question. So we cannot post the answer for your question in this question. So can you post your issue as new question by including more information? By this, it will help users including me think of the solution and post the answer. And also, I think that such answer will be useful for other users who have the same issue. If you can cooperate to resolve your issue, I'm, glad. – Tanaike Jul 01 '20 at 23:58
  • @Tanaike: can you please help me here: https://stackoverflow.com/questions/62698690/cant-access-one-drive-through-graph-api-using-azure-app Thank you! – Saurabh Chauhan Jul 02 '20 at 14:30
  • @Saurabh Chauhan Thank you for your response. I saw it just now. I noticed an answer has already been posted. In this case, I would like to respect the existing answer. And I think that it will resolve your issue. – Tanaike Jul 02 '20 at 22:50