简体   繁体   English

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

[英]how to access bearer token in vue

I'm trying to get the current user info using jwt token after successfully login, the token is saved in the browser but each time i send the request i get an error成功登录后,我尝试使用 jwt 令牌获取当前用户信息,该令牌保存在浏览器中,但每次发送请求时都会出现错误

token i get in my application tab on my console我在控制台上的应用程序选项卡中获取令牌

token:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MjM4NzA4ZDc2ZDVkMDJmZWMwNGRiZDEiLCJpYXQiOjE2NDgwODI3MTV9.xvFdGR8skZntTIdlo9aSCx90315rSoUxct_VIR9cf6Q

error i get in my console when i'm on the user route当我在用户路线上时,我进入控制台时出错

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

my script tag to get the current user info我的脚本标签获取当前用户信息


<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>

backend route for authentication用于身份验证的后端路由

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 middleware to verify the token 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"
    });
  }
};

i dont get why i'm getting an error when my token is saved in my local storage我不明白为什么当我的令牌保存在我的本地存储中时出现错误

you should see your token in console.您应该在控制台中看到您的令牌。

if you dont see, you did not save correctly.如果你没有看到,你没有正确保存。 you must check your save method.你必须检查你的保存方法。

<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>

and i arranged your middleware method.我安排了你的中间件方法。 for get token, you can split space charecter and take last index.对于获取令牌,您可以拆分空格字符并获取最后一个索引。

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