,

Login with JSON WEB Token (JWT) using Node.js + Express.js #2

Posted by


In this tutorial, we will continue building on our previous tutorial where we set up a basic Node.js server using Express.js. In this tutorial, we will focus on implementing login functionality using JSON Web Tokens (JWT) for authentication.

Step 1: Install necessary packages
First, we need to install two packages – jsonwebtoken and bcryptjs. JSON Web Tokens are used for securely transmitting information between parties as a JSON object and bcryptjs is used for hashing passwords.

To install these packages, run the following command in your terminal:

npm install jsonwebtoken bcryptjs

Step 2: Create a new route for login
Next, let’s create a new route in our server.js file for handling user login. Add the following code:

const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const app = express();

app.use(bodyParser.json());

const users = [
  {
    username: 'admin',
    password: '$2a$10$qV3D2MidFVWGfzDVDFjytuEJuJUiz3sN0Gt3snyGvri9tKC3NME2O', // hashed password for 'password'
  },
];

app.post('/login', (req, res) => {
  const { username, password } = req.body;

  const user = users.find(u => u.username === username);

  if (!user || !bcrypt.compareSync(password, user.password)) {
    return res.status(401).json({ message: 'Invalid username or password' });
  }

  const token = jwt.sign({ username: user.username }, 'secret', { expiresIn: '1h' });

  res.json({ token });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Step 3: Test the login route
Now that we have created the login route, we can test it using a tool like Postman. Send a POST request to http://localhost:3000/login with the following JSON body:

{
  "username": "admin",
  "password": "password"
}

If the credentials are correct, the server will respond with a JWT token:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.9ZU9LdG8oUfb9DZx1I5LaKei4wEyk5zgK5VCizYgbW8"
}

Step 4: Protect routes with JWT
Finally, we can protect routes in our server by checking if the JWT token is valid. We can create a middleware function to do this:

const verifyToken = (req, res, next) => {
  const token = req.headers.authorization.split(' ')[1];

  if (!token) {
    return res.status(401).json({ message: 'Token is required' });
  }

  jwt.verify(token, 'secret', (err, decoded) => {
    if (err) {
      return res.status(403).json({ message: 'Invalid token' });
    }

    req.user = decoded;
    next();
  });
};

app.get('/protected', verifyToken, (req, res) => {
  res.json({ message: 'This route is protected' });
});

In the above code, we use the verifyToken middleware to check if the JWT token is present and valid. If the token is valid, the req.user object will contain the decoded JWT payload.

That’s it! You have successfully implemented user authentication using JSON Web Tokens in your Node.js + Express.js application. Feel free to expand on this functionality by adding features like user registration, token expiration, and refresh tokens.

0 0 votes
Article Rating

Leave a Reply

22 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@0nemin199
3 hours ago

1:06:30 สำหรับใครที่ใจร้อน แล้วมองภาพไม่เข้าใจ จะบอกว่าไม่ต้องใจร้อนนะครับ ทางพี่รอยไถ ได้มีสอนใน "React Protect Route ล็อกอินแยกสิทธิ์ User & Admin | MERN Stack #8" แล้ว แต่แนะนำว่า ดูไปไล่ตาม Ep. จะดีกว่านะครับ (ปล. ผมก็เป็นคนนึงที่ใจร้อน และสงสัยมาตลอดว่าเมื่อไหร่จะมีขึ้นตอนนี้น้า ไอเราก็นึกภาพไม่ออก 5555+) ขอบคุณทาง พี่รอยไถ มากๆนะครับ

@tailengvirapong4570
3 hours ago

สอนสนุกมากครับ กด subscribe ให้เลย

@arkarapunmakaramanee9665
3 hours ago

👍👍👍

@chinnaratthuengklin2179
3 hours ago

สอนเข้าใจง่าย ไม่เร่งรีบดีครับจารย์ ขอบคุณมากๆ ครับ

@jirayutplodprong9566
3 hours ago

สอนดีมากครับ สำหรับผู้เริ่มต้น ใช้ภาษาเข้าใจง่ายเลยครับ ตอนนี้กำลังไล่ดูคลิปสอน ทำคลิปต่อไปครับผม ขอบคุณสำหรับความรู้

@Mr.JWorld
3 hours ago

สุดยอดครับขอบคุณมากครับ

@สุกัลย์คลานกระโทก
3 hours ago

ขอขอบคุณอาจารย์มากๆ นะครับ สอนดีมากๆ ผมงมอยู่หลายอาทิตย์แล้ว เจอท่านนิผมเข้าใจเหมือนท่านนั่งอยู่ข้างๆ เลย ผมดูมาหลายคนแล้วทำตาม งง สุดๆ จนเจออาจารย์แล้วเคลียร์ไปหลายคำถาม

@สุกัลย์คลานกระโทก
3 hours ago

ขอบคุณครับ เข้าใจง่าย กันเอง ชอบมากครับ ❤

@title.studio
3 hours ago

อธิบายได้เข้าใจมากๆครับ ชอบๆ ตรง กดดันตัวเอง 10 วิ 555+ สนุกมากๆครับ ผมกำลังไล่ตามทุกๆคลิปครับ ^^🤩

@กฤษฎ์กําพลภูวัชร์เดชพงศ์
3 hours ago

ขอขอบคุณ

@กฤษฎ์กําพลภูวัชร์เดชพงศ์
3 hours ago

ขอบคุณมากๆๆๆครับ เข้าใจแบบทะลุปุโหร่งเลยครับ ฟังจากที่อื่นนี่งงมากครับพิมพ์ๆตาม ไม่รู้ที่มาที่ไป แต่อาจารย์รอยไถนี่พูดแบบเคลียร์เลยครับขอบคุณอีกครั้งครับเดี๋ยวส่งเงินสนับสนุนให้ครับ

@user-13853jxjdd
3 hours ago

สอนดีกว่าคอร์สเสียตังค์อีก ขอบคุณครับ

@CodexOdyssey
3 hours ago

อยากให้สอน nux3 + crud + JSON WEB Token แทบไม่เคยเห็นช่องไหนสอนเลย

@potterpurpp809
3 hours ago

58:19 สำหรับใครที่ยัง Token Invalid อยู่ ให้ใส่ const jwt = require("jsonwebtoken");
ไว้ที่ข้างบนในไฟล์ auth.js ของ middleware นะครับ

@nantapob
3 hours ago

ขอบคุณครับ เป็นประโยชน์มากครับ เข้่าใจง่ายดีครับ

@amarinphason4124
3 hours ago

มีประโยชน์มากครับ สำหรับมือใหม่

@thewaratkhonhan9012
3 hours ago

ขอบคุณครบ สอนดีมากครับ กำลัง ไล่ดูทุกคลิปครับ55555555

@nolowcode
3 hours ago

@Sydneyyz
3 hours ago

ขอต่อเรื่อง refresh token ด้วยครับ เหมือนดูหนังไม่จบ5555

@หลอนๆหมอนอยู่ไหน-ภ1ฦ
3 hours ago

สนับสนุนค่ากาแฟให้เรียบร้อยแล้วนะคะ . ขอบคุณสำหรับความรู้ดีๆค่ะ เดี๋ยวถ้าทำเว็บเสร็จแล้วจะเอาผลงานมาให้ดูนะคะ ว่าทั้งหมดที่ทำเว็บนี้มาได้ เพราะช่องรอยไถพัฒนาทั้งหมดเลยค่ะ . ขอบคุณมากจริงๆนะคะ เวลาดูคลิปคุณ เข้าใจง่ายดีค่ะ ไม่ใช้ศัพท์คำพูดแบบเข้าใจยากเหมือนช่องอื่นที่เขาพูดกัน ชอบช่องคุณก็ตรงนี้แหล่ะค่ะ สู้ๆนะคะ ทำคลิปใหม่ๆออกมาเรื่อยๆ เราจะคอยซัพพอร์ตให้อยู่ตลอดค่ะ 😊😊

22
0
Would love your thoughts, please comment.x
()
x