Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 220
liv913 Avatar asked Feb 17 '26 19:02

liv913


1 Answers

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");

like image 89
Irshadnk Avatar answered Feb 20 '26 07:02

Irshadnk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!