我正在尝试在我的无服务器(/api
路由)next.js 应用程序中实现 Google 登录。
我正在使用@passport-next/passport-google-oauth2
,next-connect
和passport
包。
我进行了很多搜索,并在网上找到了一些有用的链接,但我无法让它工作,而且我不确定这里应该发生的整个流程。
例如,我发现了那些:
- https://github.com/andycmaj/nextjs-passport-session-auth
- https://todayilearned.io/til/nextjs-with-passport-oauth-cookie-sessions
我有/api/auth/login
定期登录的路线。如果登录成功,我将JWT
在用户响应中设置 cookie。
对于谷歌登录,我添加了/api/auth/social/google
路由,代码如下:
import passport from 'passport';
import { Strategy as GoogleStrategy } from '@passport-next/passport-google-oauth2';
import nextConnect from 'next-connect';
passport.use(new GoogleStrategy({
clientID: process.env.OAUTH_GOOGLE_CLIENT_ID,
clientSecret: process.env.OAUTH_GOOGLE_CLIENT_SECRET,
callbackURL: process.env.OAUTH_GOOGLE_CALLBACK_URL,
scope: "https://www.googleapis.com/auth/plus.login",
},
(accessToken, refreshToken, googleUserInfo, cb) => {
console.log('accessToken, refreshToken, googleUserInfo');
cb(null, googleUserInfo);
}
));
export default nextConnect()
.use(passport.initialize())
.get(async (req, res) => {
passport.authenticate('google')(req, res, (...args) => {
console.log('passport authenticated', args)
})
})
和/api/auth/social/callback/google
路线,使用以下代码:
import passport from 'passport';
import nextConnect from 'next-connect';
passport.serializeUser((user, done) => {
console.log('serialize')
done(null, user);
});
export default nextConnect()
.use(passport.initialize())
.get(async (req, res) => {
passport.authenticate('google', {
failureRedirect: '/failure/success',
successRedirect: '/auth/success',
})(req, res, (...args) => {
console.log('auth callback')
return true;
})
})
所以发生的情况是用户/auth/success
在登录到他的谷歌帐户后被重定向到,并且控制台日志是:
accessToken, refreshToken, googleUserInfo
serialize
所以我的问题是:
- 何时以及如何
JWT
在响应“登录”用户时设置 cookie? - 为什么这条线
console.log('auth callback')
永远不会运行?它应该什么时候运行? - 同样对于
console.log('passport authenticated', args)
- 我的应用程序中的完整流程应该是什么样子?
谢谢 !