简体   繁体   English

使用 Axios 和 Vue.js 进行 JWT 授权(标题)

[英]JWT Authorization with Axios and Vue.js (Header)

I'm still pretty new to web development, so I apologize in advance if the solution is obvious or my question is asked poorly.我对 Web 开发还是很陌生,所以如果解决方案很明显或者我的问题问得不好,我提前道歉。

So: I would like to use JWT to authenticate my users.所以:我想使用 JWT 来验证我的用户。 I use axios, vue.js and of course JWT.我使用 axios、vue.js,当然还有 JWT。 I would like to access a secure route:我想访问一条安全路线:

router.post('/secureroute', checkAuth, (req, res) => {
res.status(200).json({
    message: 'all ok'
})
});

In order to do so, I use this check-auth.js :为此,我使用此check-auth.js

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
 try {
    const token = req.headers.authorization.split(" ")[1];
    console.log(token);
    const decoded = jwt.verify(token, process.env.SECRET_KEY);
    next();
} catch (error) {
    return res.status(401).json({
        message: 'Auth failed'
    })
}

next();

} }

part of my Login.vue:我的 Login.vue 的一部分:

methods: {
 login() {
  if (!this.username) this.alertUsername = true;
  if (!this.password) this.alertPassword = true;

  axios
    .post("/user/login", {
      username: this.username,
      password: this.password
    })
    .then(res => {
      localStorage.setItem("usertoken", res.data.token);
      if (res.data.token) {
        console.log("Success");
        router.push({ name: "start" });
      } else {
        this.alertWrong = true;
      }
      this.username = "";
      this.password = "";
    })
    .catch(err => {
      console.log(err);
    });
  this.emitMethod();
}

Using postman with an authorization header, everything seems to work fine.使用带有授权标头的邮递员,一切似乎都正常。 But after hours of searching the Internet and trying things out, I simply do not know how to make it work with the real website.但是经过几个小时的互联网搜索和尝试,我根本不知道如何让它与真正的网站一起工作。 I would like to pass the JWT as an authorization-header.我想将 JWT 作为授权标头传递。 I know that it is possible with axios, but I really don't know how I can do so in my example here.我知道 axios 是可能的,但我真的不知道如何在我的示例中做到这一点。

You've got your login flow, and you are storing the usertoken in localStorage as the usertoken key.您已经获得了登录流程,并将用户令牌作为用户usertoken密钥存储在 localStorage 中。 You also verified that your requests are processed correctly if the authorization header is set.如果设置了授权标头,您还验证了您的请求是否得到正确处理。

The easiest way to work with api requests is by abstracting axios a bit more, to automatically add the authorization token, and maybe pre-process the response you get back.处理 api 请求的最简单方法是对 axios 进行更多抽象,以自动添加授权令牌,并可能对您返回的响应进行预处理。 For example, you may want to handle some errors globally instead of on a case-by-case basis, or want to transform the request into something that is always the same.例如,您可能希望全局处理某些错误而不是逐案处理,或者希望将请求转换为始终相同的内容。

You first want to make some abstraction that calls axios.request .您首先要进行一些调用axios.request抽象。 You can pass it a configuration object as described here .您可以按照此处的说明将配置对象传递给它。 What's most important for you right now is the headers key-value pair, but you may want to expand this in the future.现在对您来说最重要的是headers键值对,但您可能希望在将来扩展它。

export default request (config) {
  const userToken = window.localStorage.getItem('usertoken');

  const requestConfig = { ...config };
  if (!requestConfig.headers) {
    requestConfig.headers = {};
  }

  if (userToken) {
    requestConfig.headers.authorization = `Bearer ${userToken}`;
  }

  return axios.request(requestConfig);
}

Now we can expand on that:现在我们可以扩展一下:

export default post (url, data = {}, config = {}) {
  return request({
    ...config,
    method: 'POST'
    url,
    data
  });
}

When inspecting the request in your developer console you should now see that, if the user token is correctly set in localStorage, you have an extra header in your request that is sent to the server.在您的开发人员控制台中检查请求时,您现在应该看到,如果在 localStorage 中正确设置了用户令牌,则您的请求中有一个额外的标头发送到服务器。

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

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