liv913
liv913

Reputation: 117

Authentication issue with simple upload on Google Drive API

I'm trying to upload a file to my Google Drive file space, and I'm using the following code:

var httpRequest = new XMLHttpRequest();
var url_goto = "https://www.googleapis.com/upload/drive/v2/files?uploadType=media";

httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState==4 && httpRequest.status==200) {
        Firebug.Console.log(httpRequest.responseText);

    } else if (httpRequest.readyState==4 && httpRequest.status==401) {
        Firebug.Console.log(httpRequest.responseText);
    } else {
        Firebug.Console.log('Other status: ' + httpRequest.readyState + ', ' + httpRequest.status);
    }

};
var s = 'Test string';
httpRequest.open('POST', url_goto, true);
httpRequest.setRequestHeader('Content-Type', 'text/plain');
httpRequest.setRequestHeader('Content-Length', s.length);
httpRequest.setRequestHeader('Authorization', 'MY_AUTH_KEY');
httpRequest.send(s);

The problem is that I've the following output:

"Other status: 1, 0"
"Other status: 1, 0"
"Other status: 2, 401"
"Other status: 3, 401"

...and an exception is thrown:

"{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid Credentials"
 }
}"

Can anybody help me to understand why authentication is not working? I'm using the API Key retrieved from my Google APIs Console, under section Simple API Access.

Thanks!

Upvotes: 3

Views: 436

Answers (1)

Irshadnk
Irshadnk

Reputation: 91

If you are using oauth2 token then you must specify the Bear along with auth token in Authorization header like

httpRequest.setRequestHeader("Authorization", "Bearer MY_AUTH_KEY");

Upvotes: 3

Related Questions