简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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