如果您有任何使用护照 google oauth2 的nextjs项目的代码示例,请分享。网上有一些仅使用 nodejs 的示例,但路由、中间件和回调的机制与 nextjs 不同,我还没有找到工作示例。
我有以下代码,但收到 CORS 错误。我在本地主机上看过带有 google auth 演示的 youtube 视频。我创建的凭据也使用 localhost。
\lib\Passport.js
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
passport.serializeUser((user, done) => {
done(null, user._id);
});
passport.deserializeUser((req, id, done) => {
req.db
.collection('users')
.findOne({ _id: id })
.then((user) => done(null, user));
});
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: process.env.WEB_URI+"/users/callback/google",
passReqToCallback: true,
},
function(accessToken, refreshToken, profile, cb) {
// User.findOrCreate({ googleId: profile.id }, function (err, user) {
// return cb(err, user);
// });
console.log("profile below")
console.log(profile)
}
));
export default passport;
\pages\login.js 带按钮 - “使用 Google 登录”
<Button
variant="outlined"
color="secondary"
startIcon={">"}
onClick={(event) => {
googleLogin(event) }}
>
Login using Google
</Button>
和 \pages\login.js 中的功能
async function googleLogin(e) {
const res = await fetch('/api/authGoogle', {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
})
console.log(res);
return;
}
而 \pages\api\authGoogle.js
import nextConnect from 'next-connect';
import middleware from '../../middlewares/middleware';
import passport from '../../lib/passport';
const handler = nextConnect();
handler.use(middleware);
handler.get(passport.authenticate("google", {
scope: ['profile', 'email', 'openid'],
}))
handler.delete((req, res) => {
req.logOut();
res.status(204).end();
});
export default handler;
我没有的是代码users/callback/google
,我不知道该写什么。官方的passportjs 示例仅使用nodejs 并且很难遵循,因此任何使用next js 的示例将来都会对我和其他人有所帮助。