Node.js 使用下一个熨斗会话';s";withIronSession“;使用Next.JS执行简单身份验证
因此,我有一个非常简单的Next.js应用程序,我想在使用nextiron会话和withIronSession函数时添加身份验证。在api文件夹中,我有一个简单的组件,它获取登录表单数据,执行复杂的身份验证操作,然后使用 session.set(“用户”{email}) 在会话中设置用户后,我返回一个201,客户端重定向到我的受保护页面,在那里我尝试使用withIronSession作为包装器在getServerSideProps函数中获取该用户Node.js 使用下一个熨斗会话';s";withIronSession“;使用Next.JS执行简单身份验证,node.js,authentication,session-cookies,next.js,Node.js,Authentication,Session Cookies,Next.js,因此,我有一个非常简单的Next.js应用程序,我想在使用nextiron会话和withIronSession函数时添加身份验证。在api文件夹中,我有一个简单的组件,它获取登录表单数据,执行复杂的身份验证操作,然后使用 session.set(“用户”{email}) 在会话中设置用户后,我返回一个201,客户端重定向到我的受保护页面,在那里我尝试使用withIronSession作为包装器在getServerSideProps函数中获取该用户 import { withIronSession
import { withIronSession } from "next-iron-session";
export const getServerSideProps = withIronSession(
async ({ req, res }) => {
const user = req.session.get("user");
console.log(user);
if (!user) {
res.statusCode = 403;
res.end();
return { props: {} };
}
return {
props: { }
};
},
{
cookieName: 'MYSITECOOKIE',
password: "2gyZ3GDw3LHZQKDhPmPDL3sjREVRXPr8"
}
);
但是,即使在API函数中设置了用户({“user”,{email}}),同一个会话对象在我的受保护组件的getServerSideProps函数中返回{},在我的例子中,这总是导致403。是否有方法访问在getServerSideProps函数的登录组件中设置的用户
注*
我想看看这篇文章,也许它提供了更多的信息
下一个iron会话使用节点版本>12。这对我有用
import React from "react";
import { withIronSession } from "next-iron-session";
const PrivatePage = ({ user }) => (
<div>
<h1>Hello {user.email}</h1>
<p>Secret things live here...</p>
</div>
);
export const getServerSideProps = withIronSession(
async ({ req, res }) => {
const user = req.session.get("user");
if (!user) {
res.statusCode = 404;
res.end();
return { props: {} };
}
return {
props: { user }
};
},
{
cookieName: "MYSITECOOKIE",
cookieOptions: {
secure: process.env.NODE_ENV === "production" ? true : false
},
password: process.env.APPLICATION_SECRET
}
);
export default PrivatePage;
从“React”导入React;
从“下一个iron会话”导入{withIronSession};
const PrivatePage=({user})=>(
你好{user.email}
秘密的东西住在这里
);
导出常量getServerSideProps=withIronSession(
异步({req,res})=>{
const user=req.session.get(“用户”);
如果(!用户){
res.statusCode=404;
res.end();
返回{props:{};
}
返回{
道具:{user}
};
},
{
cookieName:“MYSITECOOKIE”,
Cookie选项:{
安全:process.env.NODE_env==“生产”?真:假
},
密码:process.env.APPLICATION\u SECRET
}
);
导出默认私有页面;
我相信这只会发生在http
源上。您是否在本地主机或任何其他非安全源上进行测试?如果是,则需要在cookieOptions中指定secure:false
。
从下一个iron会话的文档中
,默认设置为true
,这意味着只允许使用安全源代码(通常是使用https
的源代码)
对于开发环境,考虑使用secure:false
更新cookieOptions;对于生产环境,考虑使用secure:true
更新cookieOptions
像这样:
withIronSession(
async ({ req, res }) => {...},
{
cookieName: 'MYSITECOOKIE',
cookieOptions: {
secure: process.env.NODE_ENV === 'production' ? true : false
},
password: '2gyZ3GDw3LHZQKDhPmPDL3sjREVRXPr8'
}
);
withIronSession(
async ({ req, res }) => {...},
{
cookieName: 'MYSITECOOKIE',
cookieOptions: {
secure: process.env.NODE_ENV === 'production' ? true : false
},
password: '2gyZ3GDw3LHZQKDhPmPDL3sjREVRXPr8'
}
);