检查用户是否已登录React Js

时间:2018-06-12 15:02:35

标签: reactjs

大家好我在我的react项目中有一个JWT身份验证我想创建一个函数来检查用户是否已登录。我的登录功能是这样的:

export function login(data) {
    const endpoint = '/api/auth/jwt/'
    const csrfToken = cookie.load('csrftoken')
    let thisComp = this
    if (csrfToken !== undefined) {
      let lookupOptions = {
          method: "POST",
          headers: {
              'Content-Type': 'application/json'

          },
          body: JSON.stringify(data),
          credentials: 'include'
      }

      fetch(endpoint, lookupOptions)
      .then(function(response){
          return response.json()
      }).then(function(responseData){
          console.log(responseData)
          localStorage.token = responseData.token
          localStorage.expires = responseData.expires // Store the token
          console.log("Token Stored", localStorage.token)
          console.log("Token Expires", responseData.expires)

          refreshToken(data) // Put in to the refresh function


        }).catch(function(error){

          console.log("error", error)
      })
     }
}

我的函数isLoggedIn是这样的:

export function isLoggedIn() {
    // Check if we have a token stored 
    if (localStorage.token !== undefined) {
    // I also want to check if the token is still work and don't expire 
    // i have acces to the expiration date like this :
    // localStorage.token == > Token Expires 2018-06-19T14:51:59.451703Z in 
    the console 
    // How can check if the token still work ? 
    return true
    }
    return false

}

1 个答案:

答案 0 :(得分:0)

您是否只检查存储在本地存储中的过期属性并将其与当前日期进行比较?

处理它的其他方法:将到期日期存储在令牌本身中,然后使用jwt解码库解码令牌并从中提取它。如果您使用刷新令牌,您只需等待服务器返回401 Unauthorized响应并发送刷新令牌以请求新的令牌。