I'm building a RESTful API that uses JWT tokens for user authentication (issued by a login
endpoint and sent in all headers afterwards), and the tokens need to be refreshed after a fixed amount of time (invoking a renew
endpoint, which returns a renewed token).
It's possible that an user's API session becomes invalid before the token expires, hence all of my endpoints start by checking that: 1) the token is still valid and 2) the user's session is still valid. There is no way to directly invalidate the token, because the clients store it locally.
Therefore all my endpoints have to signal my clients of two possible conditions: 1) that it's time to renew the token or 2) that the session has become invalid, and they are no longer allowed to access the system. I can think of two alternatives for my endpoints to signal their clients when one of the two conditions occurs (assume that the clients can be adapted to either option):
- Return an http 401 code (unauthorized) if the session has become invalid or return a 412 code (precondition failed) when the token has expired and it's time to call the
renew
endpoint, which will return a 200 (ok) code. - Return 401 for signaling that either the session is invalid or the token has expired. In this case the client will immediately call the
renew
endpoint, if it returns 200 then the token is refreshed, but ifrenew
also returns 401 then it means that the client is out of the system.
Which of the two above alternatives would you recommend? Which one would be more standard, simpler to understand, and/or more RESTful? Or would you recommend a different approach altogether? Do you see any obvious problems or security risks with either option? Extra points if your answer includes external references that support your opinion.
UPDATE
Guys, please focus on the real question - which of the two http code alternatives for signaling a renewal/session invalidation is the best? Don't mind the fact that my system uses JWT and server-side sessions, that's a peculiarity of my API for very specific business rules, and not the part I'm seeking help for ;)