简体   繁体   English

如何使用axios刷新令牌?

[英]How to refresh token using axios?

I have read a lot of articles about refreshing token , but I didn't get nothing , they seems too complicated. 我已经阅读了很多关于刷新令牌的文章,但我没有得到什么,它们似乎太复杂了。 Could you please explain me on my sample. 你能帮我解释一下我的样品吗? I'm making sign-in , on response i'm getting object with access_token, refresh_token and timestamp. 我正在登录,在响应时我正在使用access_token,refresh_token和timestamp来获取对象。 After I'm saving both tokens in localStorage. 我在localStorage中保存两个令牌后。 Later when access_token expires I receive 403 error(Forbidden). 稍后当access_token到期时,我收到403错误(禁止)。 There is no message that token expired. 没有令牌过期的消息。 Could you please help me with that 你能帮我解决吗?

signIn(event) {
    event.preventDefault()
    const formdata = new FormData()
    formdata.append("username", this.state.userLogin.email)
    formdata.append("password", this.state.userLogin.password)
    axios
      .post("http://dev.****************.com/auth/get-token", formdata)
      .then(res => {
        if (res.data) {
          localStorage.setItem("token", res.data.access_token)
          localStorage.setItem("updToken", res.data.update_token)
          this.setState({
            isLoginError: false,
          })
          this.props.history.push("/settings")
        }
      })
      .catch(error => {
        if (error.response.status === 403) {
          this.setState({
            isLoginError: true,
          })
        }
      })
  }

There are two generally accepted ways to go about this: 有两种普遍接受的方法可以解决这个问题:

  1. periodically request a refreshed token based on the provided ttl in your original token -- for example, if your original token has a ttl of, say, 3600 seconds, then have a window.setInterval which refreshes every 3530 seconds. 根据原始令牌中提供的ttl定期请求刷新的令牌 - 例如,如果原始令牌的ttl为3600秒,则有一个window.setInterval ,每隔3530秒刷新一次。 This works, but doesn't handle if auth has changed for some other reason. 这有效,但如果auth因某些其他原因而发生变化,则无法处理。

  2. Better: install an http interceptor to handle a 401 and retry the request after re-authorising. 更好:安装一个http拦截器来处理401并在重新授权后重试请求。 A reasonable answer can be found here: Axios interceptors and asynchronous login 可以在这里找到一个合理的答案: Axios拦截器和异步登录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM