【问题标题】:How to refresh token using axios?如何使用 axios 刷新令牌?
【发布时间】:2019-08-21 21:23:21
【问题描述】:

我已经阅读了很多关于刷新令牌的文章,但我没有得到任何东西,它们似乎太复杂了。你能解释一下我的样品吗?我正在登录,响应时我得到带有 access_token、refresh_token 和时间戳的对象。在我将两个令牌都保存在 localStorage 中之后。后来当 access_token 过期时,我收到 403 错误(禁止)。没有令牌过期的消息。你能帮我解决这个问题吗

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,
          })
        }
      })
  }

【问题讨论】:

    标签: javascript reactjs axios token


    【解决方案1】:

    有两种普遍接受的方法来解决这个问题:

    1. 根据原始令牌中提供的 ttl 定期请求刷新令牌 - 例如,如果原始令牌的 ttl 为 3600 秒,则有一个 window.setInterval 每 3530 秒刷新一次.这有效,但如果身份验证因其他原因发生更改,则无法处理。

    2. 更好:安装http拦截器来处理401,重新授权后重试请求。可以在这里找到合理的答案:Axios interceptors and asynchronous login

    【讨论】:

    • A 403 表示用户已认证(您知道他们是谁)但未授权(不允许)。 403 应在您的应用程序中作为拒绝处理,其中 401 应导致授权挑战(刷新令牌或要求用户登录)
    猜你喜欢
    • 2020-10-01
    • 1970-01-01
    • 2020-07-12
    • 2021-06-12
    • 2022-11-03
    • 2021-06-19
    • 2016-09-23
    • 2014-09-13
    • 1970-01-01
    相关资源
    最近更新 更多