SSR框架下只能通过cookie通信,但是如何做到服务端和客户端cookie续期和过期的?大家说说自己公司如何做的,非常感谢 !
SSR框架下只能通过cookie通信,但是如何做到服务端和客户端cookie续期和过期的?大家说说自己公司如何做的,非常感谢 !
这篇文章相关讲解:我应该如何处理nuxt cookie过期和工作流程?:https://stackoverflow.com/questions/60237594/how-should-i-handle-nuxt-cookies-expiration-and-workflow
export const getToken = payload => {
return jwt.sign(payload, process.env.SEED, { expiresIn: process.env.EXPTOKEN });
}
export const checkToken = (req, res, next) => {
const rawToken = req.headers["authorization"]
if (rawToken) {
try {
const token = rawToken.substring(7)
// Verify that the token is validated
const { user, role } = jwt.verify(token, process.env.SEED);
const newToken = getToken({ user, role });
req.user = user;
req.role = role;
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.set("Access-Control-Expose-Headers", "authorization");
res.set("authorization", newToken);
} catch (error) {
if (error.name === "TokenExpiredError") {
res.set("Access-Control-Expose-Headers", "authorization");
res.set("authorization", false);
}
console.log("invalid token", error);
return new AuthenticationError
// Invalid Token
}
}
next();
}
中间件:
export default function ({ app, route, error, redirect }) {
const hasToken = !!app.$apolloHelpers.getToken()
// this part does not work
/* const tokenExpireDateTime = app.$cookies.nodeCookie.parse('cookie-name', 'expires')
if (hasToken && tokenExpireDateTime < 0) {
error({ statusCode: 403, message: 'Permission denied', description: 'Sorry, you are forbidden from accessing this page.' })
app.$apolloHelpers.onLogout()
return redirect('/login')
}
*/
if (!hasToken) {
if (route.name === 'welcome-key') {
// enrollment link route
} else {
if (route.name === 'home') {
error({ errorCode: 403, message: 'You are not allowed to see this' })
return redirect('/showcase')
}
if (!['login', 'forgot_password', 'reset_password-key'].includes(route.name)) {
error({ errorCode: 403, message: 'You are not allowed to see this' })
return redirect('/login')
}
}
} else {
if (['login', 'forgot_password', 'reset_password-key'].includes(route.name)) {
redirect('/')
}
}
}
https://nextjs.org/docs/app/api-reference/functions/cookies
8 回答4.9k 阅读✓ 已解决
6 回答3.6k 阅读✓ 已解决
5 回答2.9k 阅读✓ 已解决
5 回答6.5k 阅读✓ 已解决
4 回答2.3k 阅读✓ 已解决
4 回答2.8k 阅读✓ 已解决
3 回答2.5k 阅读✓ 已解决
问了一下chatgpt,这是它的回答:
上面说定时去刷cookie比较好,但是我觉得这会影响性能,然后我又问有比定时刷新更好的吗?
它的意思是不要用轮询的方式,而是用
window.addEventListener("focus", handleFocus);
方式监听用户动作,去后台验证cookie,如果快要过期则重新生成cookie写入到浏览器,最后感觉这个方法是优的!