首页 > 解决方案 > 将 Oauth 2.0 与 Next js 一起使用

问题描述

我想在我的 React/Next.js 应用程序中使用 Google OAuth 2.0。我已经在 Google Developer 控制台上设置了我的 OAuth 客户端 ID,并在我的 server.js 节点文件中设置了一个路由。当我尝试获取请求https://localhost:3000/auth/google时,我得到 Next js 404 Not Found 页面。它显然是在我的 Next js pages 目录中寻找一个名为 auth 的页面。尝试使用下一个/路由器,将我的按钮包装在一个锚元素中,获取 API GET 请求https://localhost:3000/auth/google,都失败了。

我已经成功地实现了护照用户身份验证、加盐、散列和会话,但只是 Oauth 给我带来了麻烦。

如果它是标准节点应用程序https://localhost:3000/auth/google将重定向到用户可以使用他们的 google 凭据登录的界面。

我已经尝试在 nextjs 示例 github 中搜索 oauth 的实现,但似乎没有。有人知道我如何将 OAuth 2.0 与 Next JS 一起使用吗?

路线

server.get("/auth/google", (req, res) =>{
   passport.authenticate("google", { scope: ['profile']});
})

应该把我带到谷歌登录/注册页面的按钮

<button className="btn btn-block btn-social btn-google" style={{'color': '#fff'}} onClick={() => Router.push("/auth/google")}>
<FontAwesomeIcon icon={faGoogle} className="google-social-button" /> Sign Up with Google
</button>

标签: oauth-2.0next.js

解决方案


你可以简单地试试这个,

const app = next({ dev });
const server = express()

server.get('/auth/google/callback*',
    passport.authenticate('google'),
(req, res) => {
    res.redirect('/dashboard');
});

server.get('/auth/google*', (req, res) => {
    return app.render(req, res, req.path, req.query)
});

server.get('/api/logout', (req, res) => {
    req.logout();
    res.send(req.user);
})

server.get('/api/current_user', (req, res) => {
    res.send(req.user);
});

server.get('*', (req, res) => {
   return handle(req, res)
});

只需确保 google reqs 在 server.get('*') 路由之上,因为它会捕获所有请求。更多帮助:https ://github.com/zeit/next.js/blob/canary/examples/custom-server-express/server.js


推荐阅读