Node.js 使用 Express-Jwt和JsonWebToken 進(jìn)行Token身份驗(yàn)證的操作方法
前言
本文將實(shí)現(xiàn)在Node.js中使用Express-Jwt和JsonWebToken進(jìn)行身份驗(yàn)證
代碼
假設(shè)一個(gè)這樣的用戶登錄場(chǎng)景,用戶在成功登錄之后,前端會(huì)向后端請(qǐng)求用戶信息,并將用戶信息渲染到頁(yè)面上。
不使用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>這是一段非常簡(jiǎn)單的代碼,點(diǎn)擊按鈕向后端請(qǐng)求用戶信息,并將其渲染到頁(yè)面上
server
/* 導(dǎo)入第三方庫(kù) */
const express = require('express')
const cors = require('cors')//解決跨域問(wèn)題
/* 創(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ǔ)的讀者看起來(lái)應(yīng)該不難理解
接下來(lái),我們將代碼升級(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>這段前端代碼不難理解,簡(jiǎn)單解釋一下就是在頁(yè)面加載的時(shí)候向服務(wù)器端請(qǐng)求token,該token中包含了用戶基本信息,待頁(yè)面加載完成后,點(diǎn)擊按鈕,可以向服務(wù)器端請(qǐng)求用戶信息,并將用戶信息渲染到頁(yè)面上。
值得注意的是,在請(qǐng)求用戶信息的時(shí)候,必須在請(qǐng)求頭中包含服務(wù)器發(fā)送的token才能有權(quán)限獲取用戶信息
后端代碼
重點(diǎn)講講后端代碼
/* 導(dǎo)入第三方庫(kù) */
const express = require('express')
const cors = require('cors')//解決跨域問(wèn)題
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)文章
node.js中的emitter.on方法使用說(shuō)明
這篇文章主要介紹了node.js中的emitter.on方法使用說(shuō)明,本文介紹了emitter.on的方法說(shuō)明、語(yǔ)法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下2014-12-12
ChatGPT編程秀之最小元素的設(shè)計(jì)示例詳解
這篇文章主要為大家介紹了ChatGPT編程秀之最小元素的設(shè)計(jì)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
Mongoose經(jīng)常返回e11000 error的原因分析
這篇文章主要給大家分析了Mongoose經(jīng)常返回e11000 error的原因,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考價(jià)值,需要的朋友可以們下面來(lái)一起看看吧。2017-03-03
Node.js服務(wù)器環(huán)境下使用Mock.js攔截AJAX請(qǐng)求的教程
Mock.js這個(gè)JavaScript庫(kù)最常見(jiàn)的用法便是被用來(lái)攔截AJAX請(qǐng)求,well,這里我們就來(lái)看一下Node.js服務(wù)器環(huán)境下使用Mock.js攔截AJAX請(qǐng)求的教程:2016-05-05
NodeJS實(shí)現(xiàn)圖片上傳代碼(Express)
本篇文章主要介紹了NodeJS實(shí)現(xiàn)圖片上傳代碼(Express) ,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06
基于nodejs+express(4.x+)實(shí)現(xiàn)文件上傳功能
通過(guò)一段時(shí)間的查閱資料發(fā)現(xiàn)實(shí)現(xiàn)上傳的方式有:1.express中間件multer模塊2.connect-multiparty模塊(但現(xiàn)在 官方不推薦 )3.使用multiparty模塊實(shí)現(xiàn)4.使用formidable插件實(shí)現(xiàn),本文給大家介紹nodejs+express(4.x+)實(shí)現(xiàn)文件上傳功能,需要的朋友參考下2015-11-11
解決node報(bào)錯(cuò)Error: Cannot find module http-e
這篇文章主要介紹了解決node報(bào)錯(cuò)Error: Cannot find module http-errors的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-05-05

