繁体   English   中英

如何在vue中访问不记名令牌

[英]how to access bearer token in vue

成功登录后,我尝试使用 jwt 令牌获取当前用户信息,该令牌保存在浏览器中,但每次发送请求时都会出现错误

我在控制台上的应用程序选项卡中获取令牌

token:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MjM4NzA4ZDc2ZDVkMDJmZWMwNGRiZDEiLCJpYXQiOjE2NDgwODI3MTV9.xvFdGR8skZntTIdlo9aSCx90315rSoUxct_VIR9cf6Q

当我在用户路线上时,我进入控制台时出错

{
    "success": false,
    "message": "Failed to authenticate"
}

我的脚本标签获取当前用户信息


<script>
import axios from "axios";
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "Welcome to Your Vue.js App"
    };
  },
  mounted() {
    axios
      .get("http://localhost:5000/api/auth/user", {
        headers: {
          Authorization: "Bearer ${token}",
          token: localStorage.getItem("token")
        }
      })
      .then(res => {
        console.log(res);
      });
  }
};
</script>

用于身份验证的后端路由

router.get("/auth/user", verifyToken, async (req, res) => {
  
    try {
      let foundUser = await User.findOne({
        _id: req.decoded._id
      }).populate(
        "address"
      );
      if (foundUser) {
        res.json({
          success: true,
          user: foundUser
        });
      }
    } catch (err) {
      res.status(500).json({
        success: false,
        message: err.message
      });
    }
  });

jwt 验证令牌的中间件

const jwt = require("jsonwebtoken");

module.exports = function (req, res, next) {
  let token = req.headers["x-access-token"] || req.headers["authorization"];
  let checkBearer = "Bearer ";

  if (token) {
    if (token.startsWith(checkBearer)) {
      token = token.slice(checkBearer.length, token.length);
    }

    jwt.verify(token, process.env.SECRET, (err, decoded) => {
      if (err) {
        console.log(err)
        res.json({
          success: false,
          message: "Failed to authenticate"
        });
      } else {
        req.decoded = decoded;

        next();
      }
    });
  } else {
    res.json({
      success: false,
      message: "No token Provided"
    });
  }
};

我不明白为什么当我的令牌保存在我的本地存储中时出现错误

您应该在控制台中看到您的令牌。

如果你没有看到,你没有正确保存。 你必须检查你的保存方法。

<script>
import axios from "axios";
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "Welcome to Your Vue.js App"
    };
  },
  mounted() {
    let token=localStorage.getItem("token");
   console.log(token);
    axios
      .get("http://localhost:5000/api/auth/user", {
        headers: {
          Authorization: `Bearer ${token}`,
          token: token
        }
      })
      .then(res => {
        console.log(res);
      });
  }
};
</script>

我安排了你的中间件方法。 对于获取令牌,您可以拆分空格字符并获取最后一个索引。

const autheticateToken = (req, res, next) => {
    var authHeader = req.headers.authorization;
    const token = authHeader?.split(' ')[1];
    if (token === null) {
        return res.json({
          success: false,
          message: "Failed to authenticate"
        });

    }
    JWT.verify(token, process.env.SECRET, (err, decoded) => {
        if (err) {
            return  res.json({
          success: false,
          message: "Failed to authenticate"
        });
        }
        req.decoded = decoded;
        next();
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM