Search code examples
node.jsexpressgoogle-apipassport.jspassport-google-oauth

How to use Passport.js Google OAuth2 strategy with Google api?


I have added passport google oauth 2.0 to my website , it works fine.

This is the initial auth call to google :

router.get("/google", 
            passport.authenticate('google',  
                                  { scope:  ["https://www.googleapis.com/auth/drive", 
                                   "https://www.googleapis.com/auth/userinfo.profile"]
          }));

But when I access the Drive API , I get an error.

For example , when I use:

  const drive = google.drive({ version: "v3", auth});
  drive.files.create(
    {
      .......
}

I get an error :

code: 401, errors: [ { domain: 'global', reason: 'required', message: 'Login Required', locationType: 'header', location: 'Authorization' } ]

Is there a way to use tokens during login and coordinate the passport login and api access ?


Solution

  • what ist auth in your example?

    Have you tried:

           const oauth2Client = new google.auth.OAuth2()
            oauth2Client.setCredentials({
                'access_token': req.user.accessToken
            });
    
            const drive = google.drive({
                version: 'v3',
                auth: oauth2Client
            });