JWT fails to check if user is logged in with API


#1

I’m using AdonisJS as an API with a Vue-CLI for the front-end.
I have no problem to log the user in. Here is my code:

  async login ({request, auth, session, response}) {
    const {email, password} = request.all()
    const user = await User.query().where('email', email).first()

    if (user) {
      const logged = await auth
        .withRefreshToken()
        .attempt(user.email, password)
      return response.status(200).json(logged)
    } else {
      return response.status(404).json(null)
    }
  }

I get an error on false credentials, and the following when the user is authenticated:

{
    "type": "bearer",
    "token": "eyJhbG...",
    "refreshToken": "cfc6dfe..."
}

The thing is, I just make sure that I the response AdonisJS contains “token” with a 200 response and not “field” or “message” with a 401 response, which would mean that the authentication failed, before redirecting to the administration part of my website. However, once on the administration part, I GET an AdonisJS route to make sure is really connected (basic check). For an unknown reason, it keeps failing, and I don’t know why.

Here is my code to check if the user is authenticated:

async logged ({auth, response}) {
    try {
      await auth.check()
      return response.status(200).json(true)
    } catch (e) {
      response.status(401).json(false)
    }
  }

If the result is false, the user is redirected to the login form. However, Somehow, it keeps returning false even though e from the catch() method is empty.

What am I doing wrong?

Thank you in advance


#2

Do you pass the token from the frontend as a header to your server?


#3

Damn, I knew I had to do something like that…
Should I set the “token” value in a cookie? Where can I find an example?

Thank you in advance


#4

Here in the docs https://adonisjs.com/docs/4.1/authentication#_jwt


#5

Actually, the main problem is that I didn’t understand correctly how JWT token worked, and I mainly needed examples. Thanks for helping!