Authenticate to Google API with Node JS

后端 未结 2 1096
刺人心
刺人心 2020-12-31 10:12

What I have so far is the app redirects to the consent page. The user accepts, then I\'m redirected back to localhost with a valid authorization code. From what I understa

2条回答
  •  情书的邮戳
    2020-12-31 10:49

    I wrote this library to get user information, hope this helps.

    'use strict'
    
    const { google } = require('googleapis')
    const credentials = require('../configs/config').google
    
    class googleApi {
        constructor(){
            const {client_id, client_secret, redirectUri } = credentials;
            this.oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirectUri)
        }
    
        generateUrl(scopes){
            const url = this.oAuth2Client.generateAuthUrl({
                access_type: 'offline',
                scope: scopes.join(' ')
            })
            return url;
        }
    
        async getUserInfo(code){
            const credentials = await this.oAuth2Client.getToken(code)
            this.oAuth2Client.setCredentials(credentials.tokens);
            const plus = google.plus({
                version: 'v1',
                auth: this.oAuth2Client,
            });
            const data = await plus.people.get({userId: 'me'});
            return data;
        }
    }
    
    module.exports = new googleApi();
    

    and this is the implementation:

    'use strict'
    const googleApi = require('../libs/google');
    
    exports.requestGmailAuth = function (req, res, next){
        let url = googleApi.generateUrl(scopes)
        res.redirect(url);
    }
    
    exports.getGmailUserInfo = async function (req, res, next){
        const qs = new url.URL(req.url, 'http://localhost:3000').searchParams;
        let code = qs.get('code')
        if(!code){
            next(new Error('No code provided'))
        }
        googleApi.getUserInfo(code)
            .then(function(response){
                res.send(response.data)
            }).catch(function(e){
                next(new Error(e.message))
        })
    }
    

    these are the routes:

    app.get('/request/gmail/auth', user.requestGmailAuth)
    app.get('/get/gmail/user', user.getGmailUserInfo)
    

    When /request/gmail/auth receives a request it redirects to consent page then the consent page redirects to /get/gmail/user with the "code" parameter.

    try this snipet and if the problem persists check your client id and client secret, and also make sure that you have google plus api enabled in your developer dashboard.

提交回复
热议问题