【问题标题】:Node JS Passport Google OAuth Not AuthenticatingNode JS Passport Google OAuth 未进行身份验证
【发布时间】:2017-04-03 03:52:42
【问题描述】:

我按照以下文档尝试为我的 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');
    }
);

应用重定向没有问题。

我应该尝试什么?我猜这与令牌有关,但我不知道要检查/修复什么。

非常感谢您。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 2011-10-20
      • 2018-02-04
      • 2017-04-03
      • 2013-05-28
      相关资源
      最近更新 更多