Reactjs React localStorage-浏览器控制台

Reactjs React localStorage-浏览器控制台,reactjs,Reactjs,嗨,我有一个关于重定向用户身份验证时的问题。当我单击login按钮并将令牌存储在localStorage上时,一切正常。但是,当我转到浏览器控制台并输入 setItem('token',test) 我可以渲染主组件,这是我不想发生的 我有这个示例代码 const isAuthenticated = () => { const authenticated = localStorage.getItem('token') return authenticated } funct

嗨,我有一个关于重定向用户身份验证时的问题。当我单击login按钮并将令牌存储在localStorage上时,一切正常。但是,当我转到浏览器控制台并输入

setItem('token',test)

我可以渲染主组件,这是我不想发生的

我有这个示例代码

const isAuthenticated = () => {
    const authenticated = localStorage.getItem('token')
    return authenticated
}

function MainHelper(){
    const history = useHistory()
    const [isAuth, setAuth] = React.useState(false)

    React.useEffect(() => {
        const token = isAuthenticated()
        if(!token){
            history.push('/login')
        }else{
            setAuth(true)
        }
    }, [isAuth, history])

    return (
        <React.Fragment>
            {isAuth === true
            ? <MainComponent />
            : null
            }
        </React.Fragment>
    )
}
const isAuthenticated=()=>{
const authenticated=localStorage.getItem('token')
返回已验证
}
函数MainHelper(){
const history=useHistory()
const[isAuth,setAuth]=React.useState(false)
React.useffect(()=>{
const token=isAuthenticated()
如果(!令牌){
history.push(“/login”)
}否则{
setAuth(真)
}
},[isAuth,历史])
返回(
{isAuth===true
? 
:null
}
)
}

只需进行API调用并检查令牌,以便第一次进行验证

if(!token){
  history.push('/login')
}else {
  fetch('your/token/validation/link', {
    method: "POST",
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer ' + token
    }}).then(() => setAuth(true))
    .catch((err) => {
         localStorage.removeItem('token');
         history.push('/login');
    })
}

您需要添加服务器存储:(示例:firebase) 使用js很容易,只需检查()

并且该服务器必须包含所有用户,在isAuth被更改后,检查服务器存储是否包含该令牌


此链接将帮助您在firebase()上设置数据库。

您不应仅依赖用户端令牌。您应该发出服务器请求并验证令牌的真实性,然后允许用户转到主应用程序。可能值得研究JWT。请在codesandbox中添加示例代码以进行调试。在捕获异常时,我还必须清除localStorage以防止无限渲染。非常感谢。这个解决方案奏效了!