简体   繁体   English

使用 JWT 令牌退出 AdonisJS

[英]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.我有一个运行良好的登录方法,它为用户生成一个 JWT 令牌以在 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).我知道我可以从客户端删除它,但问题是令牌仍然处于活动状态(例如,如果其他人以某种方式窃取此令牌,他们仍然可以访问 API)。

Any idea how to fix that?知道如何解决吗? Thanks谢谢

you should use Revoking Tokens in AdonisJs你应该在AdonisJs中使用撤销令牌

The jwt and api schemes expose methods to revoke tokens using the auth interface. jwt 和 api 方案公开了使用 auth 接口撤销令牌的方法。

For jwt, refresh tokens are only revoked, since actual tokens are never saved in the database对于 jwt,仅撤销刷新令牌,因为实际令牌从未保存在数据库中

revokeTokens(tokens, delete = false) revokeTokens(令牌,删除 = 假)

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:如果 true 作为第二个参数传递,而不是设置 is_revoked 数据库标志,相关行将从数据库中删除:

const refreshToken = '' // get it from user

await auth
  .authenticator('jwt')
  .revokeTokens([refreshToken], true)

To revoke all tokens, call revokeTokens without any arguments:要撤销所有令牌,请调用没有任何 arguments 的 revokeTokens:

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

When revoking the api token for the currently loggedin user, you can access the value from the request header:撤销当前登录用户的 api 令牌时,您可以从请求 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:此方法与 revokeTokens 方法的工作方式相同,但您可以自己指定用户:

const user = await User.find(1)

await auth
  .authenticator('jwt')
  .revokeTokensForUser(user)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM