我开始创建一个应用程序,但我不明白一些事情。我在 Nest.js 上创建了后端,在 Next.js 上创建了前端。身份验证是在后端创建的并且工作正常。我在前端做了一些事情来保护只有登录用户才能看到的路由。它正在工作,但如果我在浏览器 cookie 中设置假令牌,我可以在不登录的情况下访问这些路由...
这就是我在 Next.js(前端)上保护路由的方法:
const handleLogin = async (e: FormEvent) => {
e.preventDefault();
try {
const response = await axios.post<string>(
"http://localhost:3003/auth/administrare-site", // Replace with your backend API endpoint
formData
);
// Assuming your backend returns a token on successful login
const token = response.data;
// Store the token in local storage or a cookie for future requests
Cookies.set("token", JSON.stringify(token), {
expires: 7,
secure: true,
sameSite: "strict",
});
// Redirect to the dashboard page
router.push("/dashboard");
} catch (error) {
console.error("Error:", error);
}
};
这是前端的登录。 这里我有中间件来保护路由:
function requireAuth<T extends JSX.IntrinsicAttributes>(
Component: React.ComponentType<T>
) {
return (props: T) => {
const router = useRouter();
// Check if the 'token' cookie is present
const tokenString = Cookies.get("token");
let token = tokenString;
console.log(token);
if (!token) {
// Redirect to the login page if the token is not present
console.log('failed')
router.push("/administrare-site");
return null;
}
console.log('good')
// Render the protected component if the token is present and valid
return <Component {...props} />;
};
}
export default requireAuth;
这是我如何使用 requireAuth 来保护路由:
export default requireAuth(Dashboard);
所以问题是,在前端,令牌没有经过验证,我不知道如何在没有发现我的 JWT_SECRET 的情况下做到这一点(如果我这样做,则不安全)。不要评判我,这是我的第一个全栈应用程序,我将感谢所有的帮助。
如果您想保证 JWT 的安全,您必须在服务器端解码您的 JWT。在前端你只需验证令牌是否存在,所以这还不够。
您必须在 Nest.js 上创建一个 API 控制器,并将令牌从客户端传递到后端并验证它,如果为真,则将用户从后端重定向到您想要的位置,如果不是,则删除令牌并将用户从后端重定向到登录页面。
您也可以在 Next.js 后端执行此操作!您唯一需要的就是在 Next.js 后端验证令牌并按照我说的那样执行该过程。