Node.js 使用 Express-Jwt和JsonWebToken 進行Token身份驗證的操作方法
前言
本文將實現(xiàn)在Node.js中使用Express-Jwt和JsonWebToken進行身份驗證
代碼
假設一個這樣的用戶登錄場景,用戶在成功登錄之后,前端會向后端請求用戶信息,并將用戶信息渲染到頁面上。
不使用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>
這是一段非常簡單的代碼,點擊按鈕向后端請求用戶信息,并將其渲染到頁面上
server
/* 導入第三方庫 */ const express = require('express') const cors = require('cors')//解決跨域問題 /* 創(chuàng)建實例 */ const user = { username: 'qiuchuang', password: 123456 } const app = express() const router = express.Router() /* 路由處理函數(shù) */ router.get('/getName',(req,res)=>{ res.send(user.username) }) /* 注冊中間件 */ app.use(cors()) app.use(router) /* 注冊根路由 */ app.use('/', (req, res) => { res.send('ok') }) /* 啟動服務器 */ app.listen('80', () => { console.log('server is running at http://127.0.0.1'); })
這是后端代碼,創(chuàng)建了一個router路由處理函數(shù),響應前端請求,有一定基礎的讀者看起來應該不難理解
接下來,我們將代碼升級一下,前端不能再直接從服務器中請求數(shù)據(jù),而需要使用token認證才能獲取到用戶信息
使用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>
這段前端代碼不難理解,簡單解釋一下就是在頁面加載的時候向服務器端請求token,該token中包含了用戶基本信息,待頁面加載完成后,點擊按鈕,可以向服務器端請求用戶信息,并將用戶信息渲染到頁面上。
值得注意的是,在請求用戶信息的時候,必須在請求頭中包含服務器發(fā)送的token才能有權限獲取用戶信息
后端代碼
重點講講后端代碼
/* 導入第三方庫 */ const express = require('express') const cors = require('cors')//解決跨域問題 const jwt = require('jsonwebtoken')//生成token const expressJwt = require('express-jwt')//驗證tokne /* 創(chuàng)建實例 */ const app = express() const router = express.Router() const user = { username: 'qiuchuang', password: 123456 } const config = { jwtScrectKey: 'qiuchuang No1 ^-^',//加密密鑰 expiresIn: '10h'//有效時間 } router.get('/getToken', (req, res) => { /*生成token */ const token = jwt.sign(user,config.jwtScrectKey,{expiresIn:config.expiresIn})//將token信息掛在到user對象中 res.send(token) }) router.get('/getName',(req,res)=>{ res.send(req.user.username) }) /* 注冊中間件 */ app.use(cors()) app.use(expressJwt({secret:config.jwtScrectKey})) app.use(router) /* 注冊根路由 */ app.use('/', (req, res) => { res.send('ok') }) /* 捕獲全局錯誤的中間件 */ app.use((err, req, res, next) => { if (err.name === 'UnauthorizedError') { return res.send('身份認證失敗') } res.send(err) }) app.listen('80', () => { console.log('server is running at http://127.0.0.1'); })
讓我們看看增添了哪些代碼,
1.導入token相關的模塊
const jwt = require('jsonwebtoken')//生成token const expressJwt = require('express-jwt')//驗證tokne
2.配置對象
const config = { jwtScrectKey: 'qiuchuang No1 ^-^',//加密密鑰 expiresIn: '10h'//有效時間 }
3.響應token的路由處理函數(shù)
router.get('/getToken', (req, res) => { /*生成token */ const token = jwt.sign(user,config.jwtScrectKey,{expiresIn:config.expiresIn})//將token信息掛在到user對象中 res.send(token) })
4.注冊驗證token的中間件
app.use(expressJwt({secret:config.jwtScrectKey}))
5.處理錯誤的中間件
/* 捕獲全局錯誤的中間件 */ app.use((err, req, res, next) => { if (err.name === 'UnauthorizedError') { return res.send('身份認證失敗') } res.send(err) })
6.一處改動
res.send(user.username)
改為
res.send(req.user.username)
由于將token信息掛載到了user對象上,req多出了一個user屬性,使用這個user屬性可以根據(jù)客戶端發(fā)送的token而解析出對應的信息,也就實現(xiàn)了我們的目的-----用token進行身份認證
對比兩處代碼,相信讀者可以比較好地知道怎么實現(xiàn)基本的token身份認證,后續(xù)的代碼升級讀者也可以以此為基本,實現(xiàn)高級的功能。
到此這篇關于Node.js 使用 Express-Jwt和JsonWebToken 進行Token身份驗證的文章就介紹到這了,更多相關Node.js Token身份驗證內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
關于訪問node?express中的static靜態(tài)文件方法
這篇文章主要介紹了關于訪問node?express中的static靜態(tài)文件方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09Node.js中的HTTP?Server對象與GET、POST請求
這篇文章介紹了Node.js中的HTTP?Server對象與GET、POST請求,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07