Menu

How to protect your routes using beforeEnter in Vue Js, allowing only logged in user to navigate to it.

In Angular, you have canActivate for check for login and roles before you enter a route, in Vue Js you have beforeEnter

this is your main file in Vue Js.

import 'bootstrap';
import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App.vue';
... any other component imports
import { requireAuth } from './shared/authGuard';

Vue.use(VueRouter);

const router = new VueRouter({
	mode: 'history',
	routes:
		[
			{
				path: "/", component: AccountLayout,
				children: [
					{ path: "/", component: LoginComponent },
					{ path: "/Login", component: LoginComponent },
					{ path: "/ForgotPassword", component: ForgotPasswordComponent },
					{ path: "/PasswordReset", component: PasswordResetComponent },
					{ path: "/Logout", component: LogoutComponent },
					{ path: "/Restricted", component: RestrictedComponent }	
				]
			},
			{
				path: "/", component: ClientLayout,
				children: [
					{ path: "/Dashboard", component: StatisticComponent }					
				]
			},			
			{
				path: "Admin", component: AdminLayout, beforeEnter: requireAuth,
				children: [
					{ path: "/", component: StatisticComponent, beforeEnter: requireAuth },

					{ path: "/Users", component: UserListComponent, beforeEnter: requireAuth },
					{ path: "/Users/Edit/:id", component: UserDetailsComponent, beforeEnter: requireAuth },
					{ path: "/Users/New", component: UserDetailsComponent, beforeEnter: requireAuth },
					.......
					.......
					
				]
			},
			{ path: '*', redirect: RouteURL.Root }
		],
});

new Vue({
	el: '#app',
	router: router,
	render: h => h(App)
});

You authGuard.ts can be like this

import { tokenService } from '../services/TokenService';
import jwtDecode from 'jwt-decode';
import { RouteURL } from './constants';
import { userService } from "../services/UserService";

export function requireAuth(to: any, from: any, next: any) {
  if (!isLoggedIn()) {
    next({ path: "/Login", query: { redirect: to.fullPath }});
  } else {    
    const currentUserRole: string = userService.getCurrentRole();
    const hasAccess = userService.hasAccess(to.fullPath, currentUserRole);
    // some logic to check if user is allowed to access this route or not
    if(!hasAccess)    
      next({ path: "/Restricted" });
  
    next();
  }
}

export function isLoggedIn() {
  const token = tokenService.get();
  return !!token && !tokenService.isTokenExpired();
}

That is pretty much it.

Leave a comment