在 MERN 中,我如何管理 JWT cookie 客户端? [英] In MERN how do I manage JWT cookies client-side?

查看:45
本文介绍了在 MERN 中,我如何管理 JWT cookie 客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能向我解释如何在 MERN 堆栈中使用 cookie?我正在尝试为社交媒体制作一个模拟.我了解第一步,但后来 - 我不知道如何继续.

Can anybody explain to me how to use cookies with the MERN stack? I'm trying to make an analog for social media. I understand first steps but then - I don't know how to proceed.

  1. 我创建了用于登录、注册、注销的端点.
  2. 我创建了 React 应用程序并制作了注册表单、登录表单.然后 - 我将 axios 请求发送到我的快速端点.
  3. 快速 - 我正在保存到 MongoDB 用户或从数据库检查登录名 + 密码.
  4. 我正在创建一个带有 id 负载的 JWT 令牌并通过 cookie 发送它.

但是接下来我该怎么办?如何在反应应用程序中保存哪个用户登录?以及如何检查用户是否仍在登录并且 cookie 是否存在?感谢您的帮助!

But what do I do next? How to save which user is logged in in the react app? And how do I check if the user is still logged in and the cookie exists? Thanks for any help!

推荐答案

我有一个 repo 可以完成您想做的大部分工作.在名为 SignInForm.js 我使用 POST 请求对用户进行身份验证.如果身份验证成功,服务器会设置一个名为token"的 cookie,然后客户端重定向到一个名为 Dashboard.js. 在 Dashboard.js 中,我有以下几行代码:>

I have a repo that does much of what you are trying to do. In a React component called SignInForm.js I authenticate the user using a POST request. If the authentication is successful the server sets a cookie called 'token' and the client then redirects to a component called Dashboard.js. In Dashboard.js I have, among other things, the following lines of code:

import {useCookies} from 'react-cookie'

export const AppContext = createContext()

export default function DashBoard() {

    const [cookies, setCookie, removeCookie] = useCookies(['token'])
    let [authenticated, setAuthenticated] = useState(cookies.token !== undefined)
    
    return (
        <AppContext.Provider value={{authenticated, setAuthenticated}}>
   

上面的代码寻找名为token"的cookie.如果存在,则将身份验证设置为 true 并将其加载到 AppContext 提供程序中.服务器 API 路由当然是受保护的服务器端.但是客户端我可以使用其他组件中的身份验证值来允许或禁止访问.例如在一个名为 UserForm.js,我像这样检查身份验证(为了清楚起见,删除了一些代码):

The above code looks for the cookie called 'token'. If it exists then it sets authenticated to true and loads it into the AppContext provider. The server API routes, of course, are protected server side. But client side I can use the value of authenticated in other components to allow or disallow access. For example in a component called UserForm.js, I check authenticated like so (some code removed for clarity):

import { AppContext } from '../DashBoard'

export default function UserForm(){
    let { authenticated, setAuthenticated} = useContext(AppContext)

    if(!authenticated){
        document.location = '/signin'
        return <></>
    }

如果它们没有经过身份验证,那么我会将它们重定向到 SignIn.js 组件.

and if they aren't authenticated then I redirect them to the SignIn.js component.

这篇关于在 MERN 中,我如何管理 JWT cookie 客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆