artem

artem

Tesla: intercept 401 and refresh token on demand

Hi all

I am building a small web service that is essentially a nice looking wrapper around an external API. It reads user details from that external API, if user details list orders, then more API calls to read those orders details and present it all together in a nice looking web page.

API is oauth-authenticated and I work with it via server flow.. not sure if it’s correct name. Basically it’s my server that gets an auth token and fetches data, user doesn’t need to approve anything.

I use Tesla to access this third party API and it works very well except for when auth token expires. Then API returns 401, I need to refresh token (yet another http request) and then retry what I was doing.

It’s not a rocket science to handle it, yet still somewhat inconvenient to bake this readiness to 401+retry everywhere.

In JavaScript axios library similar situations are handled with “interceptors”. Interceptors can catch 401, “put original request on pause”, go execute another request for refreshing token, resume (or actually retry) original request wi th the renewed token.

  • Can something like this be done with Tesla as well?
  • Or what would be the proper elixir way to renew tokens on demand?

First 7 of 7 Posts Switch mode

JohnnyCurran

JohnnyCurran

Does the Retry middleware help?

Though I’m not sure if this will let you change the actual request being made, like hitting /oauth/token to get a new token if a request fails…

zorn

zorn

In my current work, I renew expired tokens (or soon to be expiring) before I do my external network calls. I added that “soon to be expiring” logic after observing some poor alignment in our Oban jobs that ran every 60m and then tokens expiring every 60m .. and full pagination capture to go past expiration.

Sorry I don’t have a good solution for you, but wanted to chime in and see what other people say too.

D4no0

D4no0

That is interesting, an approach I also wanted to try in the future. Are you refreshing the token with a job, or just on demand when you want to make a network call?

zorn

zorn

Right now, it is on demand. The module exposes a fetch_user function and to return the full list of users (which may require synchronous paginated results), we renew the token (if needed) and then start paginated requests.

There is an Oban Job that utilizes the module to do its work (which is out of cycle of normal user activity).

If you want to chat about our setup, I’m happy to do a private demo.

tangui

tangui

I wanted to write such a Tesla middleware, but didn’t have time.

However you might be interested in oauth2_token_manager: it’s very beta, but the goal is to handle token renewal among several actors. Don’t use it in prod, but you can probably get inspiration.

You’ll also have to authenticate to the OAuth2 server when renewing the token. You can use GitHub - tanguilp/tesla_oauth2_client_auth: Tesla middlewares for OAuth2 and OpenID Connect client authentication · GitHub for this which handles various client authentication schemes.

artem

artem OP

That’s what I ended up doing for now. I take expires_in value and store token to a cachex cache with TTL a little smaller than it (just in case). Next time cache is used if still available.

That said refetching on demand would be good to have - after all token an suddenly be invalid for various reasons e.g. service can reset all the tokens if some secret is leaked or maybe they keep them so that suddenly rebooted storage makes them all invalid.

As @JohnnyCurran tells, something like Retry might be useful as probably retry is retrying the whole call somehow. My elixir skills, experience and will aren’t high enough to deepen into it myself right now, but that might be a good path.

adamu

adamu

I think you could do it by using the :should_retry option.

You should pass a function that checks the result to see if it was 401.

edit: I wish we could delete posts because I realised this was not helpful right after clicking submit. As mentioned above this is no good because you also need to handle actually fetching valid credentials before retrying.

— All posts loaded —

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement