I'm looking into JWT (JSON Web Tokens) for authentication, and I have a couple of things to clarify. Is it true that when using JWTs, the client must: 1. Detect when the access token has expired, 2. Actively refresh the access token, and 3. Use the new access token until it expires? If that's the case, does that mean a basic HTTP client, like one from the 'requests' Python library, isn't equipped to handle JWTs on its own without implementing a process for these steps? In clearer terms, do I need to create a dedicated layer for JWT handling with a simple HTTP client?
3 Answers
You actually don’t need to actively track the token expiration yourself. When you get a 401 error from your request, you just call the refresh token endpoint to get a new token. So, while you’ll have to set this up for your client library, it's not exactly a requirement to always know when the token is expired beforehand.
There are two main ways to handle token refreshing: proactive and reactive. If you go with the proactive approach, you decode the token and check its expiration time. This means fewer failed requests since you won’t hit the API with an expired token, but it does require your client to manage some complexity. On the other hand, with the reactive method, you rely on the 401 errors. This keeps things simpler, but the first request after expiration will always fail, which can be troublesome depending on what type of request you're making.
Don’t forget about handling concurrent requests while refreshing the token. If your app makes multiple requests at once and the token refresh is in progress, you’ll need a way to buffer those requests to prevent any issues. If your requests are less frequent, you might want to go for preemptive token refreshing instead to keep everything smooth.
I see what you're saying, but when you mention not needing to know, it seems contradictory. If I get a 401, wouldn't it be essential to know how to handle that situation?