skip to Main Content

this my post request

app.post('/auth/google', async (req, res) => {
    try {
        const {
            code
        } = req.body;
      
    } catch (error) {
       
    }
});

i’m getting the token from my front end

 4/0AbUR2VMmkydX1bHZeUIq6xm8558a8EyxdNhc0q2ouILfp2Cc3gL3mSd3w83Qn6JJ4jaqdg

please how can i verify the code and get the user details using google-auth-library

const verifyGoogleAccessToken = async (accessToken) => {
    oauth2Client.setCredentials({
        access_token: accessToken
    });

    const userinfo = await oauth2Client.request({
        url: "https://www.googleapis.com/oauth2/v3/userinfo",
    });

    return userinfo.data;
};

please i need help,i’ve been on this for days

2

Answers


  1. Retrieve access token via authorization code. After setting the credentials for oauth2Client, there are two choices to get the user info:

    • use googleapis library
    • oauth2Client.request({url: 'https://www.googleapis.com/oauth2/v3/userinfo'})

    A working example:

    //@ts-nocheck
    import { OAuth2Client } from 'google-auth-library';
    import { google } from 'googleapis';
    import http from 'http';
    import url from 'url';
    
    const keys = require('../../../.svc/client_secret.json');
    
    const oAuth2Client = new OAuth2Client(keys.web.client_id, keys.web.client_secret, keys.web.redirect_uris[0]);
    const authorizeUrl = oAuth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: 'https://www.googleapis.com/auth/userinfo.profile',
    });
    
    http
      .createServer(async (req, res) => {
        try {
          if (req.url && req.url.indexOf('/oauth2callback') > -1) {
            const qs = new url.URL(req.url, 'http://localhost:3000').searchParams;
            const code = qs.get('code');
            console.log(`Code is ${code}`);
    
            const r = await oAuth2Client.getToken(code);
            oAuth2Client.setCredentials(r.tokens);
            console.info('Tokens acquired.');
    
            const res1 = await oAuth2Client.request({
              url: 'https://www.googleapis.com/oauth2/v3/userinfo',
            });
            console.log('res1.data: ', res1.data);
    
            const oauth2 = google.oauth2({ version: 'v2', auth: oAuth2Client });
            const res2 = await oauth2.userinfo.get();
            console.log('res2.data', res2.data);
    
            res.end('Authentication successful! Please return to the console.');
          }
        } catch (e) {
          console.error(e);
        }
      })
      .listen(3000, () => console.log(`Open ${authorizeUrl}`));
    

    Server logs:

    $ npx ts-node index.ts 
    Open https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&response_type=code&client_id=16536262744-7ob1su0o1hn4t79482e41mirhc102mvh.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Foauth2callback
    Code is 4/0AbUR2VMmkydX1bHZeUIq6xm8558a8EyxdNhc0q2ouILfp2Cc3gL3mSd3w83Qn6JJ4jaqdg
    Tokens acquired.
    res1.data:  {
      sub: '104760625496851302622',
      name: 'slideshowp2',
      given_name: 'slideshowp2',
      picture: 'https://lh3.googleusercontent.com/a/AAcHTtf5h0cmKv3cOX8AEMN9jNpaRxpU2Hv2CJEe54EL=s96-c',
      locale: 'zh-CN'
    }
    res2.data {
      id: '104760625496851302622',
      name: 'slideshowp2',
      given_name: 'slideshowp2',
      picture: 'https://lh3.googleusercontent.com/a/AAcHTtf5h0cmKv3cOX8AEMN9jNpaRxpU2Hv2CJEe54EL=s96-c',
      locale: 'zh-CN'
    }
    

    package versions:

    "google-auth-library": "^8.8.0",
    "googleapis": "^118.0.0",
    
    Login or Signup to reply.
    1. Call the Google SDK from the frontend.
    2. Extract the code or access token and send to your backend for verification.
    3. Use your backend Google api to verify the code or token.
    4. If verified, sign them in the backend and then send a response to frontend
    const express = require('express');
    const axios = require('axios');
    const cors = require('cors');
    
    const { OAuth2Client } = require('google-auth-library');
    const oauth2Client = new OAuth2Client()
    
    const app = express();
    
    // Enable CORS for all routes
    app.use(cors());
      app.post('/auth', async (req, res) => {
        try {
          const code = req.headers.authorization;
          console.log('Authorization Code:', code);
    
          // Exchange the authorization code for an access token
          const response = await axios.post(
            'https://oauth2.googleapis.com/token',
            {
              code,
              client_id: '58730156701-d27fqgjb0.apps.googleusercontent.com',
              client_secret: 'GOCSPX-u02eNiucPXxRAsQVi',
              redirect_uri: 'postmessage',
              grant_type: 'authorization_code'
            }
          );
          const accessToken = response.data.access_token;
          console.log('Access Token:', accessToken);
    
          // Fetch user details using the access token
          const userResponse = await axios.get(
            'https://www.googleapis.com/oauth2/v3/userinfo',
            {
              headers: {
                Authorization: `Bearer ${accessToken}`
              }
            }
          );
          const userDetails = userResponse.data;
          console.log('User Details:', userDetails);
    
          // Process user details and perform necessary actions
    
          res.status(200).json({ message: 'Authentication successful' });
        } catch (error) {
          console.error('Error saving code:', error);
          res.status(500).json({ message: 'Failed to save code' });
        }
      });
    
    
    app.listen(4000, () => {
        console.log('Server running on port 4000');
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search