DEV Community

Stillnoturdad
Stillnoturdad

Posted on

How to: AUTHENTICATION

When building web applications, it's important to manage user authentication securely. Two essential libraries for this are:

bcryptjs – used to hash and compare passwords securely.
JSON web token – used to sign and verify JWT tokens for user authentication.

We will cover how to implement these two libraries in your Node.js application for secure password management and token-based authentication.

How to: Use bcryptjs and jsonwebtoken in Node.js
When building web applications, it's important to manage user authentication securely. Two essential libraries for this are:

1. Install the library:

Instal package

npm install bcryptjs

Now let me show you how to do the magic.

2 . Hashing and Compare Password Like A Pro

Same old, same old, make a new js file and always remember to require the package.

const { hashSync, compareSync } = require("bcryptjs");

module.exports = {
    hashPassword: (password) => hashSync(password), 
    comparePassword: (password, hashed) => compareSync(password, hashed
};
Enter fullscreen mode Exit fullscreen mode

How it works:

hashSync(password): Hashes the user's password.
compareSync(password, hashedPassword): Compares the plain text password with the hashed version to validate user login.

3. Using jsonwebtoken for Token-Based Authentication

Install the package:

npm install jsonwebtoken

jsonwebtoken allows us to create a secure token (JWT) for each authenticated user. This token is sent to the client and can be used to authenticate the user on subsequent requests.

const { sign, verify } = require('jsonwebtoken');
const secretkey = "yoursecretkey"; // Secret key to sign the token

module.exports = {
    logToken: (payload) => log(payload, secretkey), // Create JWT token
    verifyToken: (token) => verify(token, secretkey)  // Verify JWT token
};

Enter fullscreen mode Exit fullscreen mode

How it works:
signToken(payload): Creates a signed JWT with the given payload (e.g., user data) using a secret key.

verifyToken(token): Verifies the authenticity of the JWT token using the same secret key.

Top comments (0)