我想使用 JWT使用 Google 登录 - 为此我需要 disable session并以某种方式将用户模型传递回客户端。
所有示例均使用 magically redirect to '/' 的 google 回调.
我该怎么做:
1.使用passport-google-oauth2时禁用 session 。
2. google 认证后 res.send() 用户到客户端。
如果我的方向不正确,请随时提出替代方案。
最佳答案
通过一些见解设法克服这个问题:
1. 在 express 中禁用 session - 只需删除 session 的中间件
// app.use(session({secret: config.secret}))
2。使用 Google 身份验证时,实际发生的是重定向到 google 登录页面,如果登录成功,它会将您重定向回您提供的 url。
这实际上意味着一旦谷歌调用你的回调你就不能做 res.send(token, user) - 它根本不起作用(任何人都可以解释为什么?)。因此,您必须通过执行 res.redirect("/")
来重定向到客户端。
但整个目的是传递 token ,因此您也可以执行 res.redirect("/?token="+ token)
.
app.get( '/auth/google/callback',
passport.authenticate('google', {
//successRedirect: '/',
failureRedirect: '/'
, session: false
}),
function(req, res) {
var token = AuthService.encode(req.user);
res.redirect("/home?token=" + token);
});
但是客户端如何获取用户实体呢? 因此,您也可以以相同的方式传递用户,但对我来说感觉不合适(在参数列表中传递整个用户实体......)。 所以我所做的是让客户端使用 token 并检索用户。
function handleNewToken(token) {
if (!token)
return;
localStorageService.set('token', token);
// Fetch activeUser
$http.get("/api/authenticate/" + token)
.then(function (result) {
setActiveUser(result.data);
});
}
这意味着另一个 http 请求 - 这让我觉得我可能没有正确理解 token 概念。 欢迎赐教。
关于node.js - Passport and JWT and Google Strategy - 谷歌回调后禁用 session 和 res.send(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40828955/