在 React 中使用 Httponly Cookie 持久化用户会话 [英] Persisting User Sessions with Httponly Cookies in React

查看:79
本文介绍了在 React 中使用 Httponly Cookie 持久化用户会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出在使用 HttpOnly cookie 存储会话数据时,通过 React 在客户端获取用户数据/保留用户会话的最佳方法是什么.

I'm trying to figure out what the best way is to fetch user data / persist user sessions on the client side via React, when using HttpOnly cookies to store session data.

我正在考虑做类似的事情:

I was thinking of doing something like:

useEffect( () => {

const getSession = async () => {
   const session = await fetch('/session/current')

   if(session){
       .... there is an active session
        .... set the local state to hold user data
      }   
   }

   getsession();
}

所以我想弄清楚的问题是,当用户登录并关闭浏览器,然后重新进入我的网站时.如何验证用户仍然具有有效的会话,然后将必要的用户数据发送到客户端以了解用户已通过身份验证?

So the issue I'm trying to figure out is, when the user logs in and closes the browser, then re-enters my website. How do I validate that the user still has a valid session, and then send necessary user data to the client side to know that the user is authenticated?

当用户登录并关闭浏览器时,服务器端仍然存在有效的会话HttpOnly cookie.最好的方法是点击一个端点,看看是否有一个有效的会话,然后返回用户数据?

When the user logs in and cloes the browser, there is still a valid session HttpOnly cookie on the server side. Is the best way to just hit an endpoint, see if there is a valid session, then return user data?

推荐答案

没有办法从客户端处理这个,因为它是一个 httponly cookie.您需要将 cookie 发送到后端以验证会话.如果用户关闭并重新打开浏览器,他们就会丢失 cookie.为了让他们保持登录状态,您需要跟踪来自用户的一些其他信息,例如他们的 IP 地址、操作系统、浏览器类型等,并将其保存在内存缓存中以供 ttl 使用.但这样做并不安全.

There is no way to handle this from client side as it is an httponly cookie. You need to send the cookie to the backend to validate session. If users close and reopen their browser, they loose their cookies. In order to keep them logged in you will need to track some other information from the user like their IP address, OS, browser type, etc and save it in like memory cache for a ttl. But it is not secure to do it that way.

这篇关于在 React 中使用 Httponly Cookie 持久化用户会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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