PassportJs Google Auth2 failureRedirect 不起作用
Posted
技术标签:
【中文标题】PassportJs Google Auth2 failureRedirect 不起作用【英文标题】:PassportJs Google Auth2 failureRedirect not working 【发布时间】:2018-06-21 23:44:18 【问题描述】:我正在使用 passport-google-oauth 来验证 google 登录。几乎所有东西都工作正常,但是当我从config/google.js
文件(即return done(new Error('Sorry! Your email id is not found. Please contact to Admin.'));
)返回错误时,failureRedirect
从未调用过
举例说明。请通过以下代码:-
config/google.js
module.exports = (jwt, app, passport) =>
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const User = require('../../models/user.model');
passport.use(new GoogleStrategy(
clientID: "xxxxxxxxxxxxxxxxxxxxxx",
clientSecret: "xxxxxxxxxxxxxxx",
callbackURL: "http://localhost:3000/api/user/google/callback"
,
function (accessToken, refreshToken, profile, done)
User.findOne(
email: profile.emails[0].value,
isActive: true
, function (err, user)
if (err)
return done(err);
if (!user)
return done(new Error('Sorry! Your email id is not found. Please contact to Admin.'));
else
return done(err, user);
);
));
return passport;
server.js
........
const passportGoogle = require('./server/config/auth/google')(jwt, app, passport);
const userRoute = require('./server/routes/user.route')(jwt, app, passportGoogle);
..........
user.route.js
import express from 'express';
const router = express.Router();
import User from '../models/user.model';
import UserCtrl from '../controllers/user.controller';
module.exports = (jwt, app, passportGoogle) =>
/* GET api listing. */
router.get('/', (req, res) =>
UserCtrl.getUsers()
.exec((err, users) =>
if (err)
return next(err);
res.json(users)
)
);
router.get('/google',
passportGoogle.authenticate('google', scope: ['profile', 'email'] ));
router.get('/google/callback',
passportGoogle.authenticate('google', failureRedirect: '/session/login' ),
//HERE : failureRedirect: '/session/login' :- it never called
function (req, res)
console.log('req.user', req.user)
// Successful authentication, redirect home.
res.redirect('/dashboard');
);
return router;
【问题讨论】:
【参考方案1】:done 方法应该将两个参数都设置为 null 以触发 failureRedirect。像这样,done(null, null)
【讨论】:
【参考方案2】:我只是路过,看到你的问题没有得到解答,我认为如果你想在谷歌护照策略中拒绝身份验证,你应该发送 false
作为第二个参数而不是用户在完成回调中。这将触发failureRedirect
。
function (accessToken, refreshToken, profile, done)
User.findOne(
email: profile.emails[0].value,
isActive: true
, function (err, user)
if (err)
return done(err);
if (!user)
return done(new Error('Sorry! Your email id is not found. Please contact to Admin.', false));
// Add False As Second Parameter.
else
return done(err, user);
);
));
【讨论】:
以上是关于PassportJs Google Auth2 failureRedirect 不起作用的主要内容,如果未能解决你的问题,请参考以下文章
如何确定用户是不是关闭了 google auth2.signIn() 窗口?
身份验证后使用 passportjs-google 重定向到原始页面(无会话)
如何让 Google 停止在 PassportJS 中自动登录用户?