- vừa được xem lúc

Blog#198: 🔐Authentication and Authorization in Node.js Express

0 0 6

Người đăng: NGUYỄN ANH TUẤN

Theo Viblo Asia

198

Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.

Introduction

In this article, we will discuss the core concepts of authentication and authorization in Node.js Express applications. We will explore the differences between the two, various methods for implementing them, and how to secure your applications effectively.

Understanding Authentication and Authorization

Authentication

Authentication is the process of verifying the identity of a user, device, or system. In the context of web applications, it is a mechanism to ensure that only valid users can access the protected resources.

Authorization

Authorization, on the other hand, is the process of determining what actions or resources a user is allowed to access once they are authenticated. It defines the permissions and restrictions applied to a user based on their role or attributes.

Implementing Authentication in Node.js Express

Using Passport.js

Passport.js is a popular middleware for Node.js applications that simplifies the process of authentication. It supports multiple strategies, including OAuth, OpenID Connect, and local authentication. To integrate Passport.js into your Express application, follow these steps:

  1. Install Passport.js and required strategies:
npm install passport passport-local
  1. Configure Passport.js in your application:
const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy; const app = express(); // Configure Passport Local Strategy
passport.use(new LocalStrategy( function(username, password, done) { // Authenticate user based on username and password }
)); // Configure Passport Session
passport.serializeUser(function(user, done) { done(null, user.id);
}); passport.deserializeUser(function(id, done) { // Retrieve user based on id
}); app.use(passport.initialize());
app.use(passport.session());
  1. Implement login route:
app.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login', failureFlash: true
}));

Using JSON Web Tokens (JWT)

JSON Web Tokens (JWT) is another popular method for implementing authentication in web applications. JWTs are self-contained tokens that carry user information, making them stateless and scalable. To implement JWT authentication, follow these steps:

  1. Install required packages:
npm install jsonwebtoken express-jwt
  1. Generate and sign JWT token:
const jwt = require('jsonwebtoken'); function generateToken(user) { return jwt.sign(user, process.env.JWT_SECRET, { expiresIn: '1h' });
}
  1. Implement login route:
const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt'); app.post('/login', (req, res) => { // Authenticate user based on username and password // ... const token = generateToken(user); res.json({ token });
}); // Protect routes using JWT
app.use(expressJwt({ secret: process.env.JWT_SECRET }));

Implementing Authorization in Node.js Express

Role-Based Access Control (RBAC)

Role-Based Access Control (RBAC) is a common approach for implementing authorization. It involves assigning roles to users and granting permissions to roles. To implement RBAC in your Express application, follow these steps:

  1. Define roles and permissions:
const roles = { admin: { can: ['read', 'write', 'delete'] }, user: { can: ['read'] }
};
  1. Implement a middleware to check permissions:
function can(permission) { return (req, res, next) => { const userRole = req.user.role; if (roles[userRole] && roles[userRole]. can.includes(permission)) { next(); } else { res.status(403).send('Forbidden'); } };
}
  1. Protect routes using the can middleware:
app.get('/posts', can('read'), (req, res) => { // Handle GET /posts route
}); app.post('/posts', can('write'), (req, res) => { // Handle POST /posts route
}); app.delete('/posts/:id', can('delete'), (req, res) => { // Handle DELETE /posts/:id route
});

Attribute-Based Access Control (ABAC)

Attribute-Based Access Control (ABAC) is another approach for implementing authorization, which grants permissions based on user attributes, environment, and resources. To implement ABAC in your Express application, follow these steps:

  1. Define a policy function to evaluate attributes:
function policy(user, action, resource) { if (action === 'read' && user.role === 'user') { return true; } if (action === 'write' && user.role === 'admin') { return true; } return false;
}
  1. Implement a middleware to check policies:
function checkPolicy(action, resource) { return (req, res, next) => { if (policy(req.user, action, resource)) { next(); } else { res.status(403).send('Forbidden'); } };
}
  1. Protect routes using the checkPolicy middleware:
app.get('/posts', checkPolicy('read', 'post'), (req, res) => { // Handle GET /posts route
}); app.post('/posts', checkPolicy('write', 'post'), (req, res) => { // Handle POST /posts route
});

Conclusion

In this article, we have explored the fundamentals of authentication and authorization in Node.js Express applications. We covered the differences between the two and discussed various methods for implementing them, such as Passport.js, JWT, RBAC, and ABAC. By implementing these techniques, you can effectively secure your applications and protect sensitive resources from unauthorized access.

And Finally

As always, I hope you enjoyed this article and got something new. Thank you and see you in the next articles!

If you liked this article, please give me a like and subscribe to support me. Thank you. 😊

Ref

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 502

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 414

- vừa được xem lúc

Một số phương thức với object trong Javascript

Trong Javascript có hỗ trợ các loại dữ liệu cơ bản là giống với hầu hết những ngôn ngữ lập trình khác. Bài viết này mình sẽ giới thiệu về Object và một số phương thức thường dùng với nó.

0 0 136

- vừa được xem lúc

Tìm hiểu về thư viện axios

Giới thiệu. Axios là gì? Axios là một thư viện HTTP Client dựa trên Promise.

0 0 117

- vừa được xem lúc

Imports và Exports trong JavaScript ES6

. Giới thiệu. ES6 cung cấp cho chúng ta import (nhập), export (xuất) các functions, biến từ module này sang module khác và sử dụng nó trong các file khác.

0 0 93

- vừa được xem lúc

Bài toán đọc số thành chữ (phần 2) - Hoàn chỉnh chương trình dưới 100 dòng code

Tiếp tục bài viết còn dang dở ở phần trước Phân tích bài toán đọc số thành chữ (phần 1) - Phân tích đề và những mảnh ghép đầu tiên. Bạn nào chưa đọc thì có thể xem ở link trên trước nhé.

0 0 229