0

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. After I'm saving both tokens in localStorage. Later when access_token expires I receive 403 error(Forbidden). 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,
          })
        }
      })
  }
Yerlan Yeszhanov
  • 2,149
  • 12
  • 37
  • 67

1 Answers1

0

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. This works, but doesn't handle if auth has changed for some other reason.

  2. Better: install an http interceptor to handle a 401 and retry the request after re-authorising. A reasonable answer can be found here: Axios interceptors and asynchronous login

daf
  • 1,289
  • 11
  • 16
  • A 403 implies that the user is _authenticated_ (you know _who_ they are) but not _authorized_ (not allowed). 403 should be handled as a denial within your application, where 401 should cause an authorization challenge (either refresh the token or ask the user to log in) – daf Apr 01 '19 at 19:49