node.jsjwttokenadonis.js

Logout with AdonisJS using JWT token


I have a login method working well that generates a JWT token to the user for authentication on AdonisJS. But how I could block this token in the future if the user click on "Logout" button or even if I want to block it manually by myself?

I know I could just delete it from the client side, but the problem is that the token would still being active (in the case someone else steal this token somehow they would still have access to the API, for example).

Any idea how to fix that?


Solution

  • you should use Revoking Tokens in AdonisJs

    The jwt and api schemes expose methods to revoke tokens using the auth interface.

    For jwt, refresh tokens are only revoked, since actual tokens are never saved in the database

    revokeTokens(tokens, delete = false)

    The following method will revoke tokens by setting a flag in the tokens table:

    const refreshToken = '' // get it from user
    
    await auth
      .authenticator('jwt')
      .revokeTokens([refreshToken])
    

    If true is passed as the 2nd argument, instead of setting the is_revoked database flag, the relevant row will be deleted from the database:

    const refreshToken = '' // get it from user
    
    await auth
      .authenticator('jwt')
      .revokeTokens([refreshToken], true)
    

    To revoke all tokens, call revokeTokens without any arguments:

    await auth
      .authenticator('jwt')
      .revokeTokens()
    

    When revoking the api token for the currently loggedin user, you can access the value from the request header:

    // for currently loggedin user
    const apiToken = auth.getAuthHeader()
    
    await auth
      .authenticator('api')
      .revokeTokens([apiToken])
    revokeTokensForUser(user, tokens, delete = false)
    

    This method works the same as the revokeTokens method, but instead you can specify the user yourself:

    const user = await User.find(1)
    
    await auth
      .authenticator('jwt')
      .revokeTokensForUser(user)