【发布时间】:2021-09-23 19:14:05
【问题描述】:
我在 getServerSideProps 中有这段代码,它为我提供了来自名为 token 的 cookie 的令牌值:
const token = context.req.cookies?.token || null;
const auth = true;
//Then I sent the token to server
const settings = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': "Bearer " + token,
},
body: JSON.stringify({ "limit": "10" })
};
cookie 是我从带有 Set-Cookie 标头的 post 请求中收到的 httpOnly cookie。
问题是,我想不仅在页面组件中使用令牌(getServerSideProps 仅在页面组件中)。在其他组件中,有时我想使用能够为我提供更多数据的函数,比如说客户端的所有消息 - 基于他的令牌(我在 logs.js 中将其限制为 10,并且我想在我的内部组件中增加它职能) 。通过道具传递令牌然后在我的函数中使用它是否安全?我有logs.js 组件,它有另一个名为Messages 的组件,在Messages 组件内部我想调用一个函数来获取更多消息,但我不确定它是否安全,因为获取getServerSideProps中的token是没人能看到,还是我错了?
如果我没记错的话,从客户端获取令牌以便在内部组件中发送请求的最佳方法是什么?
【问题讨论】:
标签: reactjs cookies next.js react-context