question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Interceptors] Resend failed request after Refresh Token

See original GitHub issue
// Attach the token on every request
Vue.http.interceptors.push((request, next) => {
    let token = Cookies.get('jwt.token')

    if (token) {
        request.headers = request.headers || {}
        request.headers.Authorization = `Bearer ${token}`
    }

    next()
})

// Attempts to refresh the token
Vue.http.interceptors.push((request, next) => {
   next((response) => {
        if (response.status === 401) {

           return Authentication.refresh().then((result) => {
                Cookies.set('jwt.token', result.data.token)
                request.headers.Authorization = `Bearer ${result.data.token}`

                return Vue.http(request).then((data) => {
                    return data
                })

            }).catch(() => {
                Authentication.logout()
                return router.go({name: 'login'})
            })
        }
    })
})

Everything is working fine, the token is being attached on every request and it can be refreshed.

The problem is when it tries to make the failed request(s) after it gets the new token, the request is indeed made but the response is not “passed to the vm?” so it gets always in the loading state. If I manually refresh the page it works fine.

Is there something that I am missing or is my logic/flow wrong?

PS: I think an example of a generic refresh token flow would be a good addition to the code recipes section.

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:6
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
hfalucascommented, Jul 16, 2016

@williamokano Yes the Authentication.refresh() is returning a promise 😃

export default {
    // (..)
    refresh () {
        return Vue.http.get(`${API}/v1/refresh-token`)
    }
}
0reactions
vansllycommented, Oct 8, 2017

@james2doyle That will log the user out when the original request returns an error status code like HTTP 500, instead use onrejected callback instead.

So…

// outside state that lets us know if we need to refresh or not
let allowRefresh = true;

Vue.http.interceptors.push((request, next) => {
  next((response) => {
    // are we allowed to refresh AND is this a 401?
    if (allowRefresh && response.status === 401) {
      // we can only allow them to refresh once,
      // so turn this toggle off so they will be redirected if
      // the refresh response is also a 401
      allowRefresh = false;
      return auth.refresh().then(result => {
        auth.setToken(result.data.token)
        auth.setRefreshToken(result.data.refresh_token)
        request.headers.set('Authorization', `Bearer ${result.data.token}`)

        return Vue.http(request).then(data => {
          return data
        })
      }, () => {
        auth.logout()
        return router.push('/login')
      })
    }
  })
})

That way the original error handler for the original request will handle the error for the original request.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Angular 4 Interceptor retry requests after token refresh
I am successfully caching the failed requests and can refresh the token but I cannot figure out how to resend the requests that...
Read more >
Using Axios interceptors for refreshing your API token.
After the token expires, you'll need to request a new token using the refresh token. Then, you need to use the freshly retrieved...
Read more >
Axios Interceptors tutorial with Refresh Token example
In this tutorial, I will show you how to work with Axios Interceptors: eject, error, 401 status, handling infinite loop and Refresh Token...
Read more >
Angular 4 Interceptor retry requests after token refresh
JavaScript : Angular 4 Interceptor retry requests after token refresh [ Gift : Animated Search Engine : https://bit.ly/AnimSearch ] ...
Read more >
Handle Refresh Tokens with Axios - JavaScript in Plain English
If we have many requests to refresh token in same time. Only one first request is handled by server. Rest of request will...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found