JWT token not saved on database
Asked Answered
H

1

6

A user's authentication returns the token, but it is not saved in the database

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

My Request

POST http://localhost:3333/autenticar
{
    "email":"[email protected]",
    "password": "123456"
}

My Response

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

request and response auth

My tokens table after the request 0 tokens

I found the same question on another site, but I didn't have an answer that would help.

Howard answered 9/3, 2021 at 14:1 Comment(7)
If you token is a JWT, it's normal (JWT are not saved on database, only refresh token are save)Reimer
it is JWT, but nothing is saved in the database, should something be saved?Howard
Nope. JWT is "not" (you can do it but it's useless) saved on db because token are signed. The token is only stored on the client side. Please read this document to know how JWT works : jwt.io/introduction . Only the refresh tokens are saved on the db.Reimer
now i understand,thanks broHoward
I think I should remove the question then, right?Howard
I think it is better to leave it in case any other noob also thinks it is a error lolHoward
Yes you can keep the question. I will add the answer later :) you're welcomeReimer
R
4

AdonisJS don't store JWT token in the db. Only refresh token are stored.


Why JWT token are not stored?

^ JWT are not saved on database because it's not useful. All JWT tokens are signed so the server can easily check if token is valid. Useful answer Where should I store jwt token for authentication on server side

JWT token not works like opaque token. Opaque token are saved on the database and the backend check if the token exist and then grant access.

Useful link : https://medium.com/@piyumimdasanayaka/json-web-token-jwt-vs-opaque-token-984791a3e715


Learn about JSON Web Token :

Reimer answered 9/3, 2021 at 20:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.