vuejs2 - Simple high-level overview of how to handle Vuejs authentication with JWT -
just need high level overview of how architect this. have authentication js object (es6 class) instantiated once, , uses jwt.
import { getroutebyname, getrouter } 'approuter' import axios 'axios' let instance = null class appauthentication { constructor (http, router, localstorage = window.localstorage) { if (!instance) { instance = this.storage = localstorage this.http = http // this.router = router // undefined this.api = http.create({baseurl: someurl, headers: {'authorization': 'bearer ' + this.token}}) this.watchroutes() } return instance } watchroutes () { this.router.beforeeach((to, from, next) => { let login = 'login' if (to.name !== login && this.isloggedout()) { return next(getroutebyname(login)) } next() }) } login (credentials) { return this.http.post(`${some_url}/login`, credentials) } finishauthentication (token) { this.settoken(token) this.router.replace('/') } logout () {...} set token (token) { ... } token () { ... } router: () => getrouter() // sucks isloggedin () {...} isloggedout () {...} } export default new appauthentication(axios, router /*(here router undefined)*/ )
the problem that object instantiated before vue router "ready" reference undefined. have crappy getter reaches vue router. not best way.
i have seen high level components in reactjs land wrap contents on app. haven't seen vue. what's high level way this?
something way it?
<app> <authentication> <some-tag></some-tag> <router-view></router-view> </authentication> </app>
i'm not sure understand authentication object have. recommend using vuex maintain user state rather storing in local storage. 'get token' can action , 'set token' mutation. can mirror vuex localstorage using persisted state.
here's how i've handled jwt token:
1) require token routing calls except login. in before router guard. in routes.js if using localstorage:
router.beforeeach((to, from, next) => { let = new date() if (/login|reset|activate|forgot/.test(to.path.tolowercase())) { next() } else if (localstorage.getitem('token') && localstorage.getitem('tokenexpires') > now){ next() } else { next('/login') }
2) handle 403 or other auth errors route login or wherever want go. on current app use graphql fetch , requests go through 1 graphql.js file, have 1 simple place logic dealing handling requests.
3) handle logging in api calls on login component itself, sending response vuex mutations or storing in local/session storage.
a great benefit of vue simplicity. tip: when can, put relevant functions not reusing elsewhere right on components themselves. more intuitive , makes code more maintainable going forward.
wiki
Comments
Post a Comment