【发布时间】:2020-05-18 11:21:09
【问题描述】:
我正在构建一个用户可以登录的本机应用程序。用户登录后,服务器会返回一个存储在设备上的身份验证令牌 (jwt)。这一切都有效。
现在,问题在于每当“发生”事情时对用户进行身份验证。
用户登录并存储令牌后,他被发送到屏幕'Main'。在该屏幕(以及所有其他“安全”屏幕)上,我想检查身份验证令牌。我目前有以下功能来执行此操作(简化):
// get the auth token out of the redux store
const authToken = useSelector(state => state.auth.authToken)
// the function to authenticate a user
const authenticateUser = () => {
try {
fetch('http://URL_TO_SERVER/auth/authenticate-user', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + authToken
}
})
.then(response => response.json())
.then(responseJSON => {
if (responseJSON.response === 'OK') {
// user is authenticated
} else {
// user is NOT authenticated
}
})
}
// only run the function once
useEffect(() => {
authenticateUser()
}, [])
这可行,但有一个“滞后”(因为 fetch 返回一个承诺)。当我在未登录的情况下打开应用程序并转到 I 屏幕时,屏幕仅显示一秒钟,然后,我被重定向到登录屏幕。所以它有效,但我不确定这是正确的方法。
我可以在每个屏幕上添加一个“层”并显示一个加载模式,直到 authenticateUser 函数运行,但我认为这不是正确的方法。
我的问题是:在 react 本机应用程序中保护屏幕的最佳方法是什么?我这样做的方式可以吗,还是应该换一种方式?
提前致谢!
编辑:在问这个问题之前,我已经查看了以下文章。
【问题讨论】:
标签: react-native