Trishant Pahwa
Trishant Pahwa

Reputation: 2972

Blocking JWT tokens AdonisJS

In my application, I am using JWT for authentication on the backend created in Adonis. But, I am facing an issue.

Since, JWT is stateless, it can only be logged out by deleting it from client-side. But, I require a feature in which I am trying to logout a user from server side in a case without client interaction. So, I read a few blogs and found out, the best way to make this happen is black listing the used JWT token.

But, now the issue is that if I am trying to black list, AdonisJS just saves the token, how can I blacklist it? I mean how can I compare the Authorization header that contains the complete JWT and the token that is encoded within it?

Basically how can I generate the JWT from the token column of the record that is saved by AdonisJS?

If any other way is possible please suggest.

Upvotes: 0

Views: 507

Answers (1)

Amir Hosein Salimi
Amir Hosein Salimi

Reputation: 309

TL;DR
You can simply run await auth.logout(). The token will be deleted automatically.

Long Answer:
You can define a route e.g. /user/logout
Route.get('/user/logout, 'UsersController.logout')

Then open the controller and implement the logout method. Just put this in there:
return await auth.logout()

This 1LoC will deletes the current token for the corresponding user. However, you can do this manually:
await Database.from('api_tokens').where('id', tokenId).delete()

where tokenId is the user's token.

Upvotes: 1

Related Questions