Node.js 使用 Express-Jwt和JsonWebToken 進(jìn)行Token身份驗(yàn)證的操作方法
前言
本文將實(shí)現(xiàn)在Node.js中使用Express-Jwt和JsonWebToken進(jìn)行身份驗(yàn)證
代碼
假設(shè)一個(gè)這樣的用戶登錄場景,用戶在成功登錄之后,前端會(huì)向后端請(qǐng)求用戶信息,并將用戶信息渲染到頁面上。
不使用token
web
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 引入axios -->
<script src="https://cdn.staticfile.net/axios/1.6.5/axios.js" crossorigin="anonymous"></script>
<span>用戶信息</span>
<button>獲取用戶名</button>
<script>
document.querySelector('button').onclick = function(){
axios.get('http:///127.0.0.1/getName').then(
function(response){
console.log(response);
document.querySelector('span').innerHTML = response.data
},
function(err){
console.log(err);
}
)
}
</script>
</body>
</html>這是一段非常簡單的代碼,點(diǎn)擊按鈕向后端請(qǐng)求用戶信息,并將其渲染到頁面上
server
/* 導(dǎo)入第三方庫 */
const express = require('express')
const cors = require('cors')//解決跨域問題
/* 創(chuàng)建實(shí)例 */
const user = {
username: 'qiuchuang',
password: 123456
}
const app = express()
const router = express.Router()
/* 路由處理函數(shù) */
router.get('/getName',(req,res)=>{
res.send(user.username)
})
/* 注冊(cè)中間件 */
app.use(cors())
app.use(router)
/* 注冊(cè)根路由 */
app.use('/', (req, res) => {
res.send('ok')
})
/* 啟動(dòng)服務(wù)器 */
app.listen('80', () => {
console.log('server is running at http://127.0.0.1');
})這是后端代碼,創(chuàng)建了一個(gè)router路由處理函數(shù),響應(yīng)前端請(qǐng)求,有一定基礎(chǔ)的讀者看起來應(yīng)該不難理解
接下來,我們將代碼升級(jí)一下,前端不能再直接從服務(wù)器中請(qǐng)求數(shù)據(jù),而需要使用token認(rèn)證才能獲取到用戶信息
使用token
web
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 引入axios -->
<script src="https://cdn.staticfile.net/axios/1.6.5/axios.js" crossorigin="anonymous"></script>
<span>用戶信息</span>
<button>獲取用戶名</button>
<script>
window.onload = function(){
axios.get('http://127.0.0.1/getToken').then(
function(response){
console.log(response);
},
function(err){
console.log(err);
}
)
}
document.querySelector('button').onclick = function(){
axios.get('http://127.0.0.1/getName',{
headers:{
'Authorization':`${localStorage.getItem('userToken')}`
}
}).then(
function(response){
console.log(response);
document.querySelector('span').innerHTML = response.data
},
function(err){
console.log(err);
}
)
}
</script>
</body>
</html>這段前端代碼不難理解,簡單解釋一下就是在頁面加載的時(shí)候向服務(wù)器端請(qǐng)求token,該token中包含了用戶基本信息,待頁面加載完成后,點(diǎn)擊按鈕,可以向服務(wù)器端請(qǐng)求用戶信息,并將用戶信息渲染到頁面上。
值得注意的是,在請(qǐng)求用戶信息的時(shí)候,必須在請(qǐng)求頭中包含服務(wù)器發(fā)送的token才能有權(quán)限獲取用戶信息
后端代碼
重點(diǎn)講講后端代碼
/* 導(dǎo)入第三方庫 */
const express = require('express')
const cors = require('cors')//解決跨域問題
const jwt = require('jsonwebtoken')//生成token
const expressJwt = require('express-jwt')//驗(yàn)證tokne
/* 創(chuàng)建實(shí)例 */
const app = express()
const router = express.Router()
const user = {
username: 'qiuchuang',
password: 123456
}
const config = {
jwtScrectKey: 'qiuchuang No1 ^-^',//加密密鑰
expiresIn: '10h'//有效時(shí)間
}
router.get('/getToken', (req, res) => {
/*生成token */
const token = jwt.sign(user,config.jwtScrectKey,{expiresIn:config.expiresIn})//將token信息掛在到user對(duì)象中
res.send(token)
})
router.get('/getName',(req,res)=>{
res.send(req.user.username)
})
/* 注冊(cè)中間件 */
app.use(cors())
app.use(expressJwt({secret:config.jwtScrectKey}))
app.use(router)
/* 注冊(cè)根路由 */
app.use('/', (req, res) => {
res.send('ok')
})
/* 捕獲全局錯(cuò)誤的中間件 */
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
return res.send('身份認(rèn)證失敗')
}
res.send(err)
})
app.listen('80', () => {
console.log('server is running at http://127.0.0.1');
})讓我們看看增添了哪些代碼,
1.導(dǎo)入token相關(guān)的模塊
const jwt = require('jsonwebtoken')//生成token
const expressJwt = require('express-jwt')//驗(yàn)證tokne2.配置對(duì)象
const config = {
jwtScrectKey: 'qiuchuang No1 ^-^',//加密密鑰
expiresIn: '10h'//有效時(shí)間
}3.響應(yīng)token的路由處理函數(shù)
router.get('/getToken', (req, res) => {
/*生成token */
const token = jwt.sign(user,config.jwtScrectKey,{expiresIn:config.expiresIn})//將token信息掛在到user對(duì)象中
res.send(token)
})4.注冊(cè)驗(yàn)證token的中間件
app.use(expressJwt({secret:config.jwtScrectKey}))5.處理錯(cuò)誤的中間件
/* 捕獲全局錯(cuò)誤的中間件 */
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
return res.send('身份認(rèn)證失敗')
}
res.send(err)
})6.一處改動(dòng)
res.send(user.username)
改為
res.send(req.user.username)
由于將token信息掛載到了user對(duì)象上,req多出了一個(gè)user屬性,使用這個(gè)user屬性可以根據(jù)客戶端發(fā)送的token而解析出對(duì)應(yīng)的信息,也就實(shí)現(xiàn)了我們的目的-----用token進(jìn)行身份認(rèn)證
對(duì)比兩處代碼,相信讀者可以比較好地知道怎么實(shí)現(xiàn)基本的token身份認(rèn)證,后續(xù)的代碼升級(jí)讀者也可以以此為基本,實(shí)現(xiàn)高級(jí)的功能。
到此這篇關(guān)于Node.js 使用 Express-Jwt和JsonWebToken 進(jìn)行Token身份驗(yàn)證的文章就介紹到這了,更多相關(guān)Node.js Token身份驗(yàn)證內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于訪問node?express中的static靜態(tài)文件方法
這篇文章主要介紹了關(guān)于訪問node?express中的static靜態(tài)文件方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
Node.js全局對(duì)象Global的實(shí)現(xiàn)
在Nodejs下全局變量和全局函數(shù)都是可以使用global來訪問到的,本文主要介紹了Node.js全局對(duì)象Global的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2023-12-12
Nodejs?Docker鏡像體積優(yōu)化實(shí)踐詳解
這篇文章主要為大家介紹了Nodejs?Docker鏡像體積優(yōu)化實(shí)踐示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
Node.js中的HTTP?Server對(duì)象與GET、POST請(qǐng)求
這篇文章介紹了Node.js中的HTTP?Server對(duì)象與GET、POST請(qǐng)求,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07
npm install常見錯(cuò)誤類型及對(duì)應(yīng)的解決方案
在前端開發(fā)中,npm是最常用的包管理工具,通過 npm install 命令,開發(fā)者可以輕松地安裝項(xiàng)目所需的依賴包,然而,在實(shí)際使用過程中,npm install 可能會(huì)因?yàn)楦鞣N原因而報(bào)錯(cuò),本文將詳細(xì)介紹一些常見的 npm install 錯(cuò)誤類型、發(fā)生原因及其對(duì)應(yīng)的解決方案,需要的朋友可以參考下2025-03-03

