oauth-2.0 - 将 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>
解决方案
你可以简单地试试这个,
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
推荐阅读
- javascript - 在平面列表中使用本地 img (React-Native)
- javascript - Chart JS - 更改条形图中最后一个元素的颜色
- terraform - Terraform 错误`属性“vpc_zone_identifier”的值不合适:元素 0:需要字符串。`
- nvme - 如何获取 NVMe 队列属性
- php - 如何将多个复选框值传递给php
- sql - 执行包含在 SQL Server 中的列中的字符串
- this - 这指的是对象
- c++ - 如何使用矢量元素将项目添加到结构中?
- sql - SQL Server 存储过程即使在刷新后也不刷新
- python - 调整 LSTM 模型