Reputation: 39
i'm trying to integrate JWT authentication in my client using websanova.
My problem is that on every http request, library is setting token of the response body. Here is my app.js configuration
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: '/' }
})
And i handle login like this
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) { ...
Token is recived fine on login, but then when i want to display some table, token is overwriten by table source.
local storage before and after :
Upvotes: 0
Views: 3708
Reputation: 340
The problem is in your app.js configuration inside your auth-> response function.
PROBLEM
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: '/' }
})
SOLUTION
To solve it, you should check your token value res.data and then return it only if it is a valid token. For example if the data return by the server after successfull authentication looks like {'token': '123ABC'} then your auth-> response function should look like this
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: '/' }
})
For more information you visite this page: Vue-Auth custom auth drivers
Upvotes: 1