Authentication (Xác thực) là hành động xác thực, kiểm tra người dùng có phải là một người dùng hợp lệ trong hệ thống hay không.
Authentization (Ủy quyền) là quá trình cấp cho người dùng quyền truy cập vào một tài nguyên hoặc chức năng cụ thể.
Part 1 (Viết chung file)
package.json
{
"name": "authhotext",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"dev": "nodemon dev.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module",
"description": "",
"dependencies": {
"dotenv": "^16.4.7",
"express": "^4.21.2",
"jsonwebtoken": "^9.0.2",
"nodemon": "^3.1.9"
}
}
dev.js
import express from 'express';
import jwt from 'jsonwebtoken';
import { config } from 'dotenv';
config();
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 3000;
const books = [
{
id: 1,
title: "Book 1",
content: "Content 1"
},
{
id: 2,
title: "Book 2",
content: "Content 2"
}
];
function authenToken(req,res,next) {
const authorizationHeader = req.headers['authorization'];
const token = authorizationHeader.split(' ')[1];
if(!token) res.sendStatus(401);
jwt.verify(token,process.env.ACCESS_TOKEN,(err,data) => {
if(err) res.sendStatus(403);
next();
});
}
app.get("/books",authenToken,(req,res)=> {
res.json({status: "Success",data: books});
});
app.post("/login",(req,res)=> {
// Authentication
// Authentization
const payload = req.body;
const accessToken = jwt.sign(payload,process.env.ACCESS_TOKEN,{expiresIn: '60s'});
res.json({accessToken});
});
app.listen(PORT,() => {
console.log(`Server is running at http://localhost:${PORT}`);
})
test.http
###
GET http://localhost:5000/books
Authorization: Beaer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ikxpb25lbCIsImlhdCI6MTc0MDY2NTk5MywiZXhwIjoxNzQwNjY2MDUzfQ.CVfTJ_R-tRUw2495S1bHb4yVfNHyY-9br012kUjV97c
###
POST http://localhost:5000/login
Content-Type: application/json; charset=utf-8
{
"username": "Lionel"
}
Part 2.1 (Ngoài thực tế server là khác nhau server lưu token, server trả về dữ liệu ...)
dev.js
import express from 'express';
import jwt from 'jsonwebtoken';
import { config } from 'dotenv';
config();
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 3000;
const books = [
{
id: 1,
title: "Book 1",
content: "Content 1"
},
{
id: 2,
title: "Book 2",
content: "Content 2"
}
];
function authenToken(req,res,next) {
const authorizationHeader = req.headers['authorization'];
const token = authorizationHeader.split(' ')[1];
console.log(authorizationHeader);
if(!token) res.sendStatus(401);
jwt.verify(token,process.env.ACCESS_TOKEN,(err,data) => {
if(err) res.sendStatus(403);
next();
});
}
app.get("/books",authenToken,(req,res)=> {
res.json({status: "Success",data: books});
});
app.listen(PORT,() => {
console.log(`Server is running at http://localhost:${PORT}`);
})
server.js
import express from 'express';
import jwt from 'jsonwebtoken';
import { config } from 'dotenv';
config();
const app = express();
app.use(express.json());
const PORT = process.env.PORTSERVER || 3000;
app.post("/login",(req,res)=> {
// Authentication
// Authentization
const payload = req.body;
const accessToken = jwt.sign(payload,process.env.ACCESS_TOKEN,{expiresIn: '60s'});
res.json({accessToken});
});
app.listen(PORT,() => {
console.log(`Server is running at http://localhost:${PORT}`);
})
test.http
###
GET http://localhost:5000/books
Authorization: Beaer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ikxpb25lbCIsImlhdCI6MTc0MDY2ODQwNCwiZXhwIjoxNzQwNjY4NDY0fQ.5zFlSAJE3YlMCC862umN6Eajkm6H9meYB4V_WQRafaw
###
POST http://localhost:5500/login
Content-Type: application/json; charset=utf-8
{
"username": "Lionel"
}
package.json
{
"name": "authhotext",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"dev": "nodemon dev.js",
"server": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module",
"description": "",
"dependencies": {
"dotenv": "^16.4.7",
"express": "^4.21.2",
"jsonwebtoken": "^9.0.2",
"nodemon": "^3.1.9"
}
}
Part 2.2 Create refresh token
server.js
import express from 'express';
import jwt from 'jsonwebtoken';
import { config } from 'dotenv';
config();
const app = express();
app.use(express.json());
let refreshTokens = [];
const PORT = process.env.PORTSERVER || 3000;
app.post("/login",(req,res)=> {
// Authentication
// Authentization
const payload = req.body;
const accessToken = jwt.sign(payload,process.env.ACCESS_TOKEN,{expiresIn: '60s'});
const refreshToken = jwt.sign(payload,process.env.REFRESH_TOKEN);
refreshTokens.push(refreshToken);
res.json({accessToken,refreshToken});
});
app.post("/refresh",(req,res)=> {
// Authentication
// Authentization
const refreshToken = req.body.token;
if(!refreshToken) res.sendStatus(401);
if(!refreshTokens.includes(refreshToken)) res.sendStatus(403);
jwt.verify(refreshToken,process.env.REFRESH_TOKEN,(err,data) => {
if(err) res.sendStatus(403);
const accessToken = jwt.sign({username: data.username},process.env.ACCESS_TOKEN,{
expiresIn: "360s"
});
res.json({accessToken});
});
});
app.listen(PORT,() => {
console.log(`Server is running at http://localhost:${PORT}`);
})
.env
ACCESS_TOKEN=ACCESS_TOKEN
REFRESH_TOKEN=REFRESH_TOKEN
PORT=5000
PORTSERVER=5500
dev.js
import express from 'express';
import jwt from 'jsonwebtoken';
import { config } from 'dotenv';
config();
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 3000;
const books = [
{
id: 1,
title: "Book 1",
content: "Content 1"
},
{
id: 2,
title: "Book 2",
content: "Content 2"
}
];
function authenToken(req,res,next) {
const authorizationHeader = req.headers['authorization'];
const token = authorizationHeader.split(' ')[1];
console.log(authorizationHeader);
if(!token) res.sendStatus(401);
jwt.verify(token,process.env.ACCESS_TOKEN,(err,data) => {
if(err) res.sendStatus(403);
next();
});
}
app.get("/books",authenToken,(req,res)=> {
res.json({status: "Success",data: books});
});
app.listen(PORT,() => {
console.log(`Server is running at http://localhost:${PORT}`);
})
test.http
###
GET http://localhost:5000/books
Authorization: Beaer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ikxpb25lbCIsImlhdCI6MTc0MDY3MDcyNSwiZXhwIjoxNzQwNjcxMDg1fQ.nvyIvEbt25_9KPcvj9VCHlsHbNAyXV91joqkNDh6VTk
###
POST http://localhost:5500/login
Content-Type: application/json; charset=utf-8
{
"username": "Lionel"
}
###
POST http://localhost:5500/refresh
Content-Type: application/json; charset=utf-8
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ikxpb25lbCIsImlhdCI6MTc0MDY3MDY4M30.U7-TeVqkMd97YpXae_RLQUDbxsXmR9kR59QALHPLjuQ"
}