Revoke current Api Token on Logout

How can I revoke the current used Api Token while logging out? Is there any function with which I can get the current used Api Token or do I have to do something like this:

yield request.auth.revoke(request.authUser, [request.header('Authorization').replace('Bearer ', '')])

1 Like

Hey @gencblakqori! :wave:

If I correctly understand you are using the version 3.2 of AdonisJs.
The authorization header is sent from the client, so you don’t need to clean it from your server.

Concerning the revocation of the token, you have everything you need here

Could I revoke a jwt token for specific user (es. logout) in adonis 4.
Thanks, PDP

JWT’s are stateless which means they are not stored in any database and therefore cannot be revoked. Typically they have a short lifetime and have to be renewed using a refresh token.

1 Like

How to revoke current api_token in Adonis 4?

Have you read the documentation and the link provided above? @ahmadarif

Yes I have, but it is revoke all token for the user. How to revoke just one token? @romain.lanz

Maybe use the model directly to do it? What you need is the user id and the token to revoke it.

Assuming you have the access to the user instance from the auth object.

const user = auth.current.user
const token = auth.getAuthHeader()

await user
.where('token', token)
.update({ is_revoked: true })

Also I have added a small example in the docs too

I just knew, const user = auth.current.user and auth.getAuthHeader() is available in Adonis 4, thanks for information so I don’t need to use a way const user = await auth.authenticator('api').getUser() :slight_smile:

await user
    .where('token', token)
    .update({ is_revoked: true })

But, this is not work to revoke the token.

This is my code, generate token using authenticator.generate(user). So the token is not equals with the auth header.

Sorry, this problem has been solved.
I have read this link, so the token must decrypt first before query update., my bad.

Thanks for the great framework and the response :slight_smile:

Yeah lemme see if I can add these methods directly on the auth instance, that’ll be more convenient

1 Like

working revoked in logout method

Your code will revoke all tokens, not revoke one token only.

how about like this?

try {
      const check = await auth.check();

      if (check) {
        const token = await auth.getAuthHeader();
        await auth.authenticator("jwt").revokeTokens([token]);
        return response.status(200).send({ message: "Logout successfully!" });
    } catch (error) {
      return response.send({ message: "Invalid jwt token" });