2

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":"c@gmail.com",
    "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.

crbast
  • 1,750
  • 1
  • 7
  • 16
di0n
  • 25
  • 7
  • If you token is a JWT, it's normal (JWT are not saved on database, only refresh token are save) – crbast Mar 09 '21 at 15:13
  • it is JWT, but nothing is saved in the database, should something be saved? – di0n Mar 09 '21 at 15:22
  • 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 : https://jwt.io/introduction . Only the refresh tokens are saved on the db. – crbast Mar 09 '21 at 16:35
  • now i understand,thanks bro – di0n Mar 09 '21 at 18:58
  • I think I should remove the question then, right? – di0n Mar 09 '21 at 19:00
  • I think it is better to leave it in case any other noob also thinks it is a error lol – di0n Mar 09 '21 at 19:09
  • Yes you can keep the question. I will add the answer later :) you're welcome – crbast Mar 09 '21 at 20:18

1 Answers1

1

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 :

crbast
  • 1,750
  • 1
  • 7
  • 16