JWT authentication with Vue.js JWT authentication with Vue.js vue.js vue.js

JWT authentication with Vue.js


You can do global headers, and when the user is authenticated, add to the global headers the token like this example , I'm using Axios.

axios.defaults.headers.common['Authorization'] = "Bearer"+  authtoken.token

For checking the authentication of the user or to manage parts of your website, simply add global variable, and when the user is authenticated set the variable to true. Alternatively, use Vuex and it will be easy and the element you want to hide or to show to the user simply add v-if to the element like (example using Vuex)

<div v-if="this.$store.state.authenticated"> Hide Element from Guests </div>

And for the route, in your routes add meta field to indicate the path is requires authentication

{        path: '/dashboard',        component: DashboardPage,        name: 'Dashboard',        meta: {requiresAuth: true} // Meta Field , you can name it }

In your Vue Router configuration add navigating guards that check the presence of the meta field, and if true check the if the user is authenticated

const router = new VueRouter({ ... })router.beforeEach((to, from, next) => {  if(to.meta.requiresAuth) { // check the meta field     if(store.state.Authenticated) { // check if the user is authenticated        next() // the next method allow the user to continue to the router     }    else {        next('/') // Redirect the user to the main page    }}else {    next()}})