我正试图在我的无服务器(/api路由) next.js应用程序中实现Google。
我正在使用@passport-next/passport-google-oauth2、next-connect和passport包。
我搜索了很多,并在网上找到了一些有用的链接,但我无法使它发挥作用,我也不确定这里应该发生的整个流程。
例如,我发现:
我有定期登录的/api/auth/login路径。如果登录成功,我将在用户响应上设置JWT cookie。
对于Google登录,我添加了/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;
})
})因此,在登录到他的google帐户后,用户被重定向到/auth/success,控制台日志如下:
accessToken, refreshToken, googleUserInfo
serialize所以我的问题是:
JWT cookie以“登录”用户?console.log('auth callback')从未运行?什么时候应该运行?console.log('passport authenticated', args)中应该是这样的。
谢谢!
发布于 2021-02-09 17:43:48
我也有同样的问题。我仍然在进行完整的实现,但是根据this thread的说法,问题可能是passport.authenticate应该被用作中间件:
// api/auth/social/callback/google
export default nextConnect()
.use(passport.initialize())
.get(passport.authenticate("google"), (req, res) => {
console.log('auth callback')
res.writeHead(302, {
'Location': '/auth/success'
});
res.end();
})发布于 2020-11-04 22:23:40
好的,我不是Next.js专家,但我遇到了类似的“问题”,只使用其他身份验证方法。
您可以看到,框架有一个在身份验证过程中非常重要的方法,它们被称为:getInitialProps,,它是一个异步函数,可以作为静态方法添加到任何页面,以便在初始呈现之前触发;
看起来是这样的:
static async getInitialProps(ctx) {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const json = await res.json()
return { stars: json.stargazers_count }
}它使用这个ctx支柱,它是一个具有{req,res}的对象,您可以使用该对象来对用户进行身份验证,然后,您可以使用req和lib next-cookies来获取JWT令牌并检查它是否有效,然后,您可以返回一个对象,该对象将用作您页面的支柱(或者所有页面,如果您将_app.js包装在身份验证的上下文中的话)。
另外,您的'auth回调‘没有被调用,因为您在它触发之前重定向用户,这是没有发生的。同样适用于‘护照认证’
这篇文章也可能对你有所帮助。https://dev.to/chrsgrrtt/easy-user-authentication-with-next-js-18oe
https://stackoverflow.com/questions/64688195
复制相似问题