后端用node前端vue怎么实现jwt鉴权

后端用node前端vue怎么实现jwt鉴权

npm install jsonwebtoken --save

然后,下面是一个简单的例子,说明如何在 Node.js 后端和 Vue.js 前端中使用 JWT 进行用户身份验证。

  1. 后端:
    const express = require('express');
    const jwt = require('jsonwebtoken');
    const app = express();
    
    // 设置 JWT 加密密钥,保存在环境变量或文件中更安全
    const JWT_SECRET = 'my_secret_key';
    
    // 登录请求
    app.post('/api/login', (req, res) => {
      const username = req.body.username;
      const password = req.body.password;
    
      // 在数据库中验证用户名和密码是否正确,验证通过之后生成 token 并返回给前端
      if (username === 'admin' && password === '123456') {
        const user = { id: 1, username: 'admin' };
        const token = jwt.sign(user, JWT_SECRET);
        res.json({ token: token });
      } else {
        res.status(401).json({ error: 'Unauthorized access' });
      }
    });
    
    // 需要进行身份验证的 API 请求
    app.get('/api/data', verifyToken, (req, res) => {
      // 通过验证,处理 API 逻辑
      res.json({ message: 'Hello, JWT' });
    });
    
    // 验证 JWT token 的中间件
    function verifyToken(req, res, next) {
      // 获取请求头中的 token
      const token = req.headers.authorization ? req.headers.authorization.split(' ')[1] : null;
    
      if (token === null) {
        res.status(401).json({ error: 'Unauthorized access' });
        return;
      }
    
      // 验证 token 是否有效
      jwt.verify(token, JWT_SECRET, (err, decoded) => {
        if (err) {
          res.status(401).json({ error: 'Unauthorized access' });
          return;
        }
    
        // 在请求中继续使用该 token
        req.token = token;
        req.user = decoded;
        next();
      });
    }
    
    // 启动服务器
    app.listen(3000, () => {
      console.log('Server is listening on port 3000.');
    });

    前端

  2. <template>
      <div>
        <h1>{{ message }}</h1>
      </div>
    </template>
    
    <script>
    import axios from 'axios';
    
    export default {
      data() {
        return {
          message: ''
        };
      },
      created() {
        // 在发送 API 请求前,将 token 添加到请求头,携带用户身份验证信息
        const token = localStorage.getItem('token');
        if (token) {
          axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        }
    
        axios
          .get('/api/data')
          .then(response => {
            this.message = response.data.message;
          })
          .catch(error => {
            console.log(error);
            if (error.response.status === 401) {
              this.$router.push('/login'); // 跳转到登录页面
            }
          });
      }
    };
    </script>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值