[英]How can I use JSESSIONID (session cookie) for authentication in React?
So, I'm fetching data from an API that is built in Liferay (json web service) and in which I'm to integrate into a React frontend.因此,我从 Liferay(json Web 服务)中内置的 API 获取数据,并将在其中集成到 React 前端。 Right now I'm at the stage where I need to authenticate a user, and I'm halfway there.
现在,我正处于需要对用户进行身份验证的阶段,并且已经完成了一半。 I'm currently sending a post-request with the Fetch API, to a specific endpoint that is defined in the backend.
我目前正在使用 Fetch API 向后端定义的特定端点发送一个后请求。 From there I get back some user data in JSON format, but also a JSESSIONID cookie.
从那里我得到一些 JSON 格式的用户数据,还有一个 JSESSIONID cookie。 I'm mostly used to using json web tokens for authentication and basically what I need to know how to use this session cookie in a similar way.
我主要习惯于使用 json Web 令牌进行身份验证,基本上我需要知道如何以类似的方式使用此会话 cookie。
I'm thinking in my mind I want to store the cookie in a state/context, and let the application determine if there is a session, and only then be able to access protected routes, etc, but I'm not entirely sure this is the way you do it.我在想我想将cookie存储在状态/上下文中,并让应用程序确定是否存在会话,然后才能访问受保护的路由等,但我不完全确定这一点是你这样做的方式。
I would really be glad if someone could point me in the right direction.如果有人能指出我正确的方向,我真的很高兴。
The context to verify that the user is authenticated.验证用户是否已通过身份验证的上下文。
import * as React from 'react'
export const AuthContext = React.createContext({})
const AuthProvider = ({
children
}) => {
const [dataUser, setDataUser] = React.useState({})
const Data = async () => {
const user = await fetch('url')
const resp = await user.json()
setDataUser(resp)
//cookies or localStorage
localStorage.setItem('user', resp)
}
React.useEffect(() => {
Data()
}, [])
const existUser = () => {
return JSON.parse(localStorage.user).id === dataUser.id
}
const Auth = existUser()
return(
<AuthContext.Provider value={{dataUser, setDataUser, Auth}}>
{children}
</AuthContext.Provider>
)
}
export default AuthProvider
put the provider in the app将提供程序放在应用程序中
const App = () => {
return(
<AuthProvider>
<Pages />
</AuthProvider>
)
}
export default App
build the pages that need authentication, using useContext, or a custom react hook.使用 useContext 或自定义反应钩子构建需要身份验证的页面。
const DashBoard = ({}) => {
const { Auth } = React.useContext(AuthContext)
const isAuth = () => {
Auth ?? window.location('url') // or react router history
}
React.useEffect(() => {
isAuth()
}, [])
return(
<>
{Auth && //optional
<div>
<h1>DashBoard</h1>
</div>
}
</>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.