Vue-auth websanova

时间:2018-02-06 11:16:47

标签: authentication vue.js jwt

我正在尝试使用websanova在我的客户端中集成JWT身份验证。

我的问题是,在每个http请求中,库都设置了响应主体的标记。这是我的app.js配置

Vue.use(VueAxios, axios)
Vue.use(VueAuth, {
  auth: {
    request: function (req, token) {
      req.headers['Authorization'] = 'JWT ' + token;
    },
    response: function (res) {
      return res.data
    }
  },
  http: require('@websanova/vue-auth/drivers/http/axios.1.x.js'),
  router: require('@websanova/vue-auth/drivers/router/vue-router.2.x.js'),
  loginData: { url: 'http://localhost:5005/api/authenticate', fetchUser: false },
  fetchData: { enabled: false },
  refreshData: { enabled: false },
  authRedirect: { path: '/' }
})

我处理这样的登录

login () {
this.$store.dispatch("login");
var redirect = this.$auth.redirect();
  this.$auth.login({
  headers: {
    'Content-Type': 'application/json'
  },
data: this.data.body,
rememberMe: this.data.rememberMe,
redirect: { name: redirect ? redirect.from.name : 'Home' },
fetchUser: false,
success (res) {
  this.$store.dispatch("login_success");
},
err (err) { ...

令牌在登录时被罚款,但是当我想显示某个表时,令牌会被表源覆盖。

之前和之后的本地存储: local storage before and after

1 个答案:

答案 0 :(得分:1)

问题在于身份验证中的app.js配置 - > 响应 功能。

问题

Vue.use(VueAxios, axios)
Vue.use(VueAuth, {
  auth: {
    request: function (req, token) {
      req.headers['Authorization'] = 'JWT ' + token;
    },
    response: function (res) {
      return res.data   //HERE IS THE PROBLEM (You need to check the token and return it only when it is valid token)
    }
  },
  http: require('@websanova/vue-auth/drivers/http/axios.1.x.js'),
  router: require('@websanova/vue-auth/drivers/router/vue-router.2.x.js'),
  loginData: { url: 'http://localhost:5005/api/authenticate', fetchUser: false },
  fetchData: { enabled: false },
  refreshData: { enabled: false },
  authRedirect: { path: '/' }
})

要解决此问题,您应检查您的令牌值 res.data ,然后仅在它是有效令牌时才返回它。 例如,如果成功进行身份验证后服务器返回的数据类似于 {'token':'123ABC'} ,那么您的身份验证 - > 响应 功能应如下所示

Vue.use(VueAxios, axios)
Vue.use(VueAuth, {
  auth: {
    request: function (req, token) {
      req.headers['Authorization'] = 'JWT ' + token;
    },
    response: function (res) {

      //TEST IF DATA CONTAINS VALID AND RETURN IT. 
      if(res.data.token)
         return res.data.token  

      //DON'T RETURN ANY VALUE IF THERE IS NO VALID TOKEN
    }
  },
  http: require('@websanova/vue-auth/drivers/http/axios.1.x.js'),
  router: require('@websanova/vue-auth/drivers/router/vue-router.2.x.js'),
  loginData: { url: 'http://localhost:5005/api/authenticate', fetchUser: false },
  fetchData: { enabled: false },
  refreshData: { enabled: false },
  authRedirect: { path: '/' }
})

有关详情,请访问此页面:Vue-Auth custom auth drivers