节点JS Passport Google OAuth无法进行身份验证

时间:2017-04-03 03:52:43

标签: javascript node.js authentication oauth google-oauth

我按照以下文档尝试为我的nodeJS应用程序设置Google OAuth:https://cloud.google.com/nodejs/getting-started/authenticate-users

我的oauth2.js代码如下:

const express = require('express');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

function extractProfile (profile) {
    let imageUrl = '';
    if (profile.photos && profile.photos.length) {
        imageUrl = profile.photos[0].value;
    }
    return {
        id: profile.id,
        displayName: profile.displayName,
        image: imageUrl
    };
}
passport.use(new GoogleStrategy({
    clientID: <CLIENT ID as string>,
    clientSecret: <CLIENT SECRET as string>,
    callbackURL: 'http://<APP DOMAIN>/auth/google/callback'
}, (accessToken, refreshToken, profile, cb) => {
    cb(null, extractProfile(profile));
}));
passport.serializeUser((user, cb) => {
    cb(null, user);
});
passport.deserializeUser((obj, cb) => {
    cb(null, obj);
});
const router = express.Router();
function authRequired(req, res, next){
    if(!req.user){
        req.session.oauth2return = req.originalUrl;
        return res.redirect('/auth/login');
    }
    next();
}
function addTemplateVariables(req, res, next){
    res.locals.profile = req.user;
    res.locals.login = `/auth/login?return=${encodeURIComponent(req.originalUrl)}`;
    res.locals.logout = `/auth/logout?return=${encodeURIComponent(req.originalUrl)}`;
    next();
}

router.get(
    '/auth/login',
    (req, res, next) => {
        if(req.query.return) {
            req.session.oauth2return = req.query.return;
        }
        next();
    },
    passport.authenticate('google', {scope: ['email', 'profile']})
);

router.get('/auth/google/callback',
    passport.authenticate('google', {
        successRedirect: '/index',
        failureRedirect: '/'
    })
);

router.get('/auth/logout', (req, res)=>{
    req.logout();
    res.redirect('/');
});

module.exports = {
    extractProfile: extractProfile,
    router: router,
    required: authRequired,
    template: addTemplateVariables
};

似乎其他一切都运转正常。我被重定向到Google OAuth同意屏幕,登录后,我应该选择ALLOW(授予权限)。 但是,当我被重定向到/ auth / google / callback时, passport.authenticate('google' ... 部分未进行身份验证,我收到404 Not Found错误(不是GET错误)。

我知道重定向工作正常,因为如果我尝试

router.get('/auth/google/callback',
    function(req, res){
        res.redirect('/index');
    }
);

该应用重定向没有问题。

我该怎么办?我猜它与令牌有关,但我不知道要检查/修复什么。

提前非常感谢你。

1 个答案:

答案 0 :(得分:1)

http://voidcanvas.com/googles-oauth-api-node-js/ 我最后使用googleapis包,按照上面链接中的步骤操作。它像魔术一样工作;)