Node.js 使用 Express-Jwt和JsonWebToken 进行Token身份验证

前言

本文将实现在Node.js中使用Express-Jwt和JsonWebToken进行身份验证

代码

假设一个这样的用户登录场景,用户在成功登录之后,前端会向后端请求用户信息,并将用户信息渲染到页面上。

不使用token
web
html 复制代码
<!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
javascript 复制代码
/* 导入第三方库 */

const express = require('express')

const cors = require('cors')//解决跨域问题

/* 创建实例 */

const user = {

    username: 'qiuchuang',

    password: 123456

}

const app = express()

const router = express.Router()

/* 路由处理函数 */

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');
})

这是后端代码,创建了一个router路由处理函数,响应前端请求,有一定基础的读者看起来应该不难理解

接下来,我们将代码升级一下,前端不能再直接从服务器中请求数据,而需要使用token认证才能获取到用户信息

使用token

web
html 复制代码
<!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中包含了用户基本信息,待页面加载完成后,点击按钮,可以向服务器端请求用户信息,并将用户信息渲染到页面上。

值得注意的是,在请求用户信息的时候,必须在请求头中包含服务器发送的token才能有权限获取用户信息

后端代码

重点讲讲后端代码

javascript 复制代码
/* 导入第三方库 */

const express = require('express')

const cors = require('cors')//解决跨域问题

const jwt = require('jsonwebtoken')//生成token

const expressJwt = require('express-jwt')//验证tokne

/* 创建实例 */

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相关的模块
javascript 复制代码
const jwt = require('jsonwebtoken')//生成token

const expressJwt = require('express-jwt')//验证tokne
2.配置对象
javascript 复制代码
const config = {

    jwtScrectKey: 'qiuchuang No1 ^-^',//加密密钥

    expiresIn: '10h'//有效时间

}
3.响应token的路由处理函数
javascript 复制代码
router.get('/getToken', (req, res) => {

    /*生成token */

    const token = jwt.sign(user,config.jwtScrectKey,{expiresIn:config.expiresIn})//将token信息挂在到user对象中

    res.send(token)

})
4.注册验证token的中间件
javascript 复制代码
app.use(expressJwt({secret:config.jwtScrectKey}))
5.处理错误的中间件
javascript 复制代码
/* 捕获全局错误的中间件 */

app.use((err, req, res, next) => {

    if (err.name === 'UnauthorizedError') {
        return res.send('身份认证失败')
    }

    res.send(err)

})
6.一处改动
javascript 复制代码
res.send(user.username)

改为

javascript 复制代码
res.send(req.user.username)

由于将token信息挂载到了user对象上,req多出了一个user属性,使用这个user属性可以根据客户端发送的token而解析出对应的信息,也就实现了我们的目的-----用token进行身份认证

对比两处代码,相信读者可以比较好地知道怎么实现基本的token身份认证,后续的代码升级读者也可以以此为基本,实现高级的功能。

OK,今天的分享就到这里,我是秋窗,我们下期再见👋

相关推荐
只睡四小时1 天前
MCP 弃用 SSE?Node 分帧漏 81.7% 事件
node.js·webassembly·实时通信·mcp·streamable http
hey you~1 天前
个体户门店办理400电话,如何对接订单系统实现来电弹窗
node.js·webhook·400电话·门店数字化·来电弹窗·订单系统对接
YIAN2 天前
RAG 学到最后,我真正学会的不是“检索”,而是让系统知道自己缺什么
langchain·node.js·llm
用户11977079480732 天前
GitHub 电商开源项目分享:用 sharp 批量出饰品主图,试了裁剪、细节图和色彩配置文件三个坑
前端·node.js
donecoding2 天前
pnpm 配好了,为什么执行的还是另一份?命令入口与运行时排查
node.js·前端工程化
江屿风2 天前
【Plain Language Large Model】【从浏览器到全栈:一课精通Node.js三剑客】流食般投喂
笔记·前端框架·npm·node.js·js·npx
SomeOtherTime3 天前
node.js基础(AI回答)
node.js
雨季mo浅忆3 天前
记录Node.js安全漏洞及其内置Brotli解码器问题
node.js·安全性测试
tommyjiatong3 天前
资安底座连环雷:从 PHP2Shell 到 Node2Shell
node.js·php
SEO_juper4 天前
Bash 交叉验证 robots.txt 和 sitemap:两个文件自相矛盾,页面永远收录不了
开发语言·python·node.js·json·bash