Authentication JWT Trouble

Hi there, I’m having some trouble with JWT authentication. I think it’s not generating the token.

controller :

async login({request, response, auth}) {
        const {username,password} = request.only(['username', 'password'])
        
        const token = await auth.authenticator('jwtadmin').attempt(username, password)
        response.status(200).json({
            message: "success",
            token: token,
        })
    }

model/TblMstAdmin.js

'use strict'
/** @type {import('@adonisjs/framework/src/Hash')} */
const Hash = use('Hash')

/** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */
const Model = use('Model')

class TblMstAdmin extends Model {
    static boot () {
        super.boot()

        /**
         * A hook to hash the user password before saving
         * it to the database.
         */
        this.addHook('beforeSave', async (userInstance) => {
        if (userInstance.dirty.password) {
            userInstance.password = await Hash.make(userInstance.password)
        }
        })
    }
    tokens () {
        return this.hasMany('App/Models/TblMstTokenadmin')
    }
}

module.exports = TblMstAdmin

config/auth.js

jwtadmin: {
    serializer: 'lucid',
    model: 'App/Models/TblMstAdmin',
    scheme: 'jwt',
    uid: 'username',
    password: 'password',
    options: {
      secret: Env.get('APP_KEY')
    }
  },

but i try post via postman always result

[{"field":"username","message":"Cannot find user with provided username"}]

this is my table admin
tbl_admin
this is my table token
tbl_token

what the problem

1 Like
  1. The ‘token’ table is only used when you authenticate with ‘sessions’. Tokens generated with JWT authentication are stateless i.e. the tokens are not stored.
  2. I think the error is very explanatory. Ensure that the ‘username’ exists on the table i.e. the record is inserted into the table.
1 Like