Auth methods, jwt tokens & password hashing in AdonisJs

In this tutorial, we are going to learn about the Auth methods, jwt tokens & password hashing in AdonisJs.
Submitted by Radib Kar, on February 06, 2021

In our last tutorial, you must have got to learn how to write the user controller to implement register & login facilities. There you saw an auth method which is auth.attempt() which takes the login credential and tries to attempt to login. In our last tutorial, we also talked about the jwt token.

Here, we will check more details on jwt tokens, auth methods. As an additional thing, we will also look at how passwords are stored in the database.

So in our last article, we saw once a registered user logs in it returns the jwt token(of course we are returning via our controller function!)

Are you wondering what if we decode this jwt token?

Well, let's grab the jwt token and head on to jwt.io, paste it and see what you are finding as to the decoded message.

auth methods (1)

auth methods (2)

So, there you go, the decoded payload shows the id, right? Check with another user and see whether you can see the corresponding user id or not.

Auth methods

In our last tutorial, we used auth.attempt() method. Here we will discuss more auth methods.

When the authenticator is 'jwt'

  1. auth.attempt()
    This helps to login validating the credentials you pass as arguments. An example is like below,
    await auth.attempt(email, password)
    
  2. auth.generate()
    This generates jwt token for a valid user. An example is like below:
    const user = await User.find(id)
    await auth.generate(user)//provided user is valid object, not null
    
  3. auth.getUser()
    This reveals the user who is logged in (we will use this further in our project, task controllers)
    try {
      return await auth.getUser()
    } catch (error) {
      response.send('Missing or invalid jwt token')
    }
    
  4. auth.check()
    This checks whether jwt token has been sent through request header or not(user logged in or not)
    try {
      await auth.check()
    } catch (error) {
      response.send('Missing or invalid jwt token')
    }
    

Similarly, you can find auth methods if you use other authenticators like sessions which are pretty much same. But here we will not discuss them a lot since we ware using jwt as the authenticator. If you are interested, then please follow the doc page for details here (https://adonisjs.com/docs/4.1/authentication#_authenticators)




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.