My goal is to develop a plugin to manage the OAuth2 token data in my Vue.js application.
I followed several tutorials available on the internet to create this plugin.
var plugin = {}
plugin.install = function (Vue, options) {
var authStorage = {
getToken () {
let token = localStorage.getItem('access_token')
let expiration = localStorage.getItem('expiration')
if (!token || !expiration) {
return null
}
if (Date.now() > parseInt(expiration)) {
this.destroyToken()
return null
}
return token
},
setToken (accessToken, expiration, refreshToken) {
localStorage.setItem('access_token', accessToken)
localStorage.setItem('expiration', expiration + Date.now())
localStorage.setItem('refresh_token', refreshToken)
},
destroyToken () {
localStorage.removeItem('access_token')
localStorage.removeItem('expiration')
localStorage.removeItem('refresh_token')
},
isAuthenticated () {
if (this.getToken()) {
return true
} else {
return false
}
}
}
Vue.prototype.$authStorage = authStorage
}
export default plugin
However, when I attempt to access the methods in the main.js file, I encounter an error indicating that the object is undefined.
import Vue from 'vue'
import App from './App'
import router from './router'
import AuthStorage from './AuthStorage.js'
Vue.config.productionTip = false
Vue.use(AuthStorage)
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuth)) {
if (!Vue.$authStorage.getToken()) {
next({
path: '/',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next()
}
})
axios.defaults.headers.common = {
'Authorization': `Bearer ${Vue.$authStorage.getToken()}`
}
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
https://i.stack.imgur.com/eYO0x.png
While the plugin works as expected inside the components, I am facing issues when trying to use it in the main.js file. I have already attempted with: - this.$authStorage - this.authStorage - Vue.authStorage
Unfortunately, none of these approaches were successful.