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.

Help me with my middleware oauth retry request, using refresh token

See original GitHub issue

I am developing a middleware that puts my autorizathion token in the request, and identifies if it has experienced, has expired, I make a new request with the refresh token, and then I need to redo the initial request, but I only have thenext()inside the response, How do I change the old token for the new one? and the next does not accept parameters.

response(next) {
    return new Promise((resolve, reject) => {
      next()
        .then(resp => resolve(resp))
        .catch((resp) => {
          const accessToken = resp.request().headers().authorization;
          const refreshToken = retrieveRefreshToken();
          const status = resp.responseStatus;
          if (accessToken && refreshToken && status === 401) {
            refreshAuth(refreshToken, resp)
              .then((newRequest) => {
                next(); // in here i need insert new token. ps: request.response().enhance() not working
              })
              .catch(() => {
                reject(resp);
              });
          } else {
            reject(resp);
          }
        });
    });
  },

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
tulioscommented, Apr 17, 2018

Version 2.20.0 is out, give it a try. I’ll consider this solved for now but feel free to create a new issue or to comment on this one.

Thanks for the reporting!

2reactions
tulioscommented, Apr 16, 2018

Hey, commit 6d85a110c75d5fc43fc8323cd40d6e788840940d introduces a new feature called “renew”. Now, from the response phase of a middleware you can re-run the middleware stack.

example:

const AccessTokenMiddleware = () => {
  // maybe this is stored elsewhere, here for simplicity
  let accessToken = null

  return () => ({
    request(request) {
      return Promise
        .resolve(accessToken)
        .then((token) => token || fetchAccessToken())
        .then((token) => {
          accessToken = token
          return request.enhance({
            headers: { 'Authorization': `Token ${token}` }
          })
        })
    },
    response(next, renew) {
      return next().catch(response => {
        if (response.status() === 401) { // token expired
          accessToken = null
          return renew()
        }

        return next()
      })
    }
  })
}

In this example, I’m running the middleware stack after receiving a token expired (401). I think you can adapt this to your needs.

If you can, please try out the code in master. I’ll probably release a new version tomorrow. What do you think about the solution, would it solve your problem? Thanks.

NOTE: I’ve played with different options, including accepting a new request object in the next function but this could cause some issues when you have a stack with several middlewares configured. This approach preserves the lifecycle and makes sure all middlewares are re-executed.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using Refresh Tokens in ASP.NET Core Authentication
Refresh tokens are credentials that can be used to acquire new access tokens. When access tokens expire, we can use refresh tokens to...
Read more >
What Are Refresh Tokens and How to Use Them Securely
This post will explore the concept of refresh tokens as defined by OAuth 2.0. We will learn how they compare to other token...
Read more >
Retry logic with different access token in Angular http client
One user can have different refresh tokens for different API, and I don't know how to manage access token when access token is...
Read more >
Refresh Tokens - OAuth 2.0 Simplified
To use the refresh token, make a POST request to the service's token endpoint with grant_type=refresh_token , and include the refresh token as ......
Read more >
Using Axios interceptors for refreshing your API token.
I'm using Redis to store the token and refresh token received from the API as you can see in the examples. Obvious code...
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