OAuth2.0 token strange behaviour (Invalid Credentials 401)

后端 未结 13 1648
無奈伤痛
無奈伤痛 2020-12-05 00:13

Usually, Google OAuth2.0 mechanism is working great.

  1. The user confirms permission to access Google account with selected scopes.
  2. The refresh token is
13条回答
  •  生来不讨喜
    2020-12-05 00:22

    I ran into this same problem when I needed to change my scopes from Read Only to Read And Write All Files. So, I updated my scopes from at the top of my file from Read Only to:

    // If modifying these scopes, delete your previously saved credentials
    // at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
    var SCOPES = ['https://www.googleapis.com/auth/drive'];
    

    Google, from their API guide, has these comments that say whenever you change scopes, you must update credentials. I believe this means, although I am not certain, that the token must be updated. The old token is still held by Google and it thought that I only had Read Only access, hence why it would return a 401 error. So, I need to remake my token, but Google never offered a new consent screen that would allow me to say allow Read And Write To All Files. So, I needed to get that screen to come up again, so it would create a new token to replace the old one:

    fs.readFile(TOKEN_PATH, function(err, token) {
        if (err) {
          getNewToken(oauth2Client, callback);
        } else {
            getNewToken(oauth2Client, callback);
        //   oauth2Client.credentials = JSON.parse(token);
        //   callback(oauth2Client);
        }
      });
    

    Since I already had a saved token, it was never creating a new one. So, I just commented out the using of the old token and told it to get a new token, no matter if we have one or not. Then, I went to my Connected Apps in Google and deleted my old connecting credential. I'm not sure if this step is necessary, but I am only trying to access my personal account. Then, when I ran my program, it prompted me to re-authenticate, and everything worked and I did not receive an authentication error. Once done, make sure to remove the commented out lines for using already made tokens. I was using the Google API quickstart.js file for all of this.

    So, when I updated my scopes, the old token was still using the Read Only scope, therefore I would get (401) Invalid Credentials.

提交回复
热议问题