【问题标题】:JWT token not saved on databaseJWT 令牌未保存在数据库中
【发布时间】:2021-03-09 14:01:55
【问题描述】:

用户认证返回token,但没有保存在数据库中

AuthController:

'use strict'

const User = use("App/Models/User");

class AuthController {
  async registrar({ request }) {
    const data = request.only(["username", "email", "password"]);

    const user = await User.create(data);

    return user;
  }

  async autenticar({ request, auth }) {
    const { email, password } = request.all();
    const retorno = {};
    let token;
    if (token = await auth.attempt(email, password)) {
      const user = await User.findBy('email', email)
      retorno.token = token.token;
      retorno.user = user.username;
      retorno.id = user.id;
    } else {
      retorno.data = "E-mail ou senha Incorretos";
    }
    return retorno;
  }

}

module.exports = AuthController

我的请求

POST http://localhost:3333/autenticar
{
    "email":"c@gmail.com",
    "password": "123456"
}

我的回应

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjEsImlhdCI6MTYxNTI5Njk4MH0.O0X4gGIEtMiZfEH3VxWbffsCZQDUhgEv0CymA0dB6z8",
  "user": "gui",
  "id": 1
}

request and response auth

请求后我的令牌表 0 tokens

我在另一个网站上发现了同样的问题,但没有找到有用的答案。

【问题讨论】:

  • 如果token是JWT,正常(JWT不存入数据库,只存刷新token)
  • 是JWT,但是数据库里什么都没有保存,是不是应该保存一些东西?
  • 不。 JWT 是“不”(您可以这样做,但它没用)保存在 db 上,因为令牌已签名。令牌仅存储在客户端。请阅读此文档以了解 JWT 的工作原理:jwt.io/introduction。只有刷新令牌保存在数据库中。
  • 现在我明白了,谢谢兄弟
  • 我想我应该删除这个问题,对吧?

标签: authentication jwt adonis.js


【解决方案1】:

AdonisJS 不会在数据库中存储 JWT 令牌。仅存储refresh token


为什么不存储 JWT 令牌?

^ JWT 没有保存在数据库中,因为它没有用。所有 JWT 令牌都经过签名,因此服务器可以轻松检查令牌是否有效。有用的答案Where should I store jwt token for authentication on server side

JWT 令牌不像不透明令牌那样工作。不透明令牌保存在数据库中,后端检查令牌是否存在,然后授予访问权限。

有用的链接:https://medium.com/@piyumimdasanayaka/json-web-token-jwt-vs-opaque-token-984791a3e715


了解 JSON Web 令牌:

【讨论】:

    猜你喜欢
    • 2019-05-19
    • 2017-12-25
    • 2020-12-25
    • 1970-01-01
    • 2018-06-21
    • 2021-09-23
    • 1970-01-01
    • 2019-12-15
    • 2018-11-12
    相关资源
    最近更新 更多