Jwt revoke method not working


#1

I have working rest API functionality in Adonis 4. I am creating logout endpoint with passing header for current user i cant able to revoke / delete that jwt token still its working other endpoints

My code is

const user = await auth.getUser() ---- in example auth.current.user ( its not working thats why i am using this)
response.send({ message: user});
const token = auth.getAuthHeader();
console.log(token)
let play = await user
.tokens()
.where(‘type’, ‘api_token’)
.where(‘is_revoked’, false)
.whereNot(‘token’, Encryption.decrypt(token))
.update({ is_revoked: true })
console.log("____________" + play)

Output : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjYsImlhdCI6MTUxMzU4NDU5OX0.W1C745wnKtz-i302zHXSl1F9-lzab6TnUFfMjnSxGa0
____________0

but still that Jwt working. tell me any solutions


#2

JWT’s are stateless which means they are not stored in any database and therefore cannot be revoked. Logging out a user is as simple as deleting the token from the user’s local storage.
To prevent a JWT from being used, choose a small expiration time. The user then has to renew his JWT using a refresh token which is stored server side and therefore can be revoked.


#3

Thanks bro. nice sharing


#4

How and where to renew it?
Docs don’t help much. I don’t want to force users to log in again I would like to renew it dynamically when a user hits a route, for example his profile page. Do I implement that on a controller associated with that route or do I need some kind of a service?


#5

This is very well documented here: https://adonisjs.com/docs/4.0/authentication#_jwt
I personally refresh the JWT on a regular basis in my SPA’s (setInterval()). Alternatively you could check the expiration time before every request. You then would have a route like “/auth/refresh” and handle auth.generateForRefreshToken(refreshToken) inside a AuthController.


#6

Yeah, I was to consider a separate route and logic inside AuthController. But I think I have problem with auth:jwt and middleware stack. I would appreciate if you could look at this thread for additional info and express some thoughts about that. Generate new jwt token after its expiration


#7

So how I would approach this is by trying to generate a new token whenever any api returns 401. Step by step

  1. Make API request and receives 401.
  2. Consider this as the expiration of the token. Use the refresh token to generate a new token.
  3. Got new token, retry the previous API call.
  4. Refresh token failed to get a new token? Consider something bad, and ask the user to login and get a new token via login flow.

And yes there needs to be a route to get the JWT token from the refresh token.


#8

Thanks @virk, I will instruct the frontend team to follow these steps. Looks good.