How to implement role-based auth in Vue
Implementing role-based authentication in Vue ensures users only access features and routes appropriate for their permission level and organizational role. As the creator of CoreUI with extensive Vue experience since 2014, I’ve built role-based systems for enterprise applications requiring granular access control and user management. The most secure approach uses Vue Router guards combined with composables to check user roles before allowing route access and component rendering. This method provides comprehensive authorization while maintaining clean, testable code architecture throughout your Vue application.
Use Vue Router guards and composables to implement role-based access control for routes and components.
import { ref, computed } from 'vue'
import router from '@/router'
// Auth composable
export function useAuth() {
const user = ref(null)
const roles = ref([])
const hasRole = (role) => {
return roles.value.includes(role)
}
const hasAnyRole = (roleList) => {
return roleList.some(role => roles.value.includes(role))
}
const login = async (credentials) => {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credentials)
})
const data = await response.json()
user.value = data.user
roles.value = data.user.roles
localStorage.setItem('token', data.token)
}
return { user, roles, hasRole, hasAnyRole, login }
}
// Route guard
router.beforeEach((to, from, next) => {
const { user, hasRole, hasAnyRole } = useAuth()
if (to.meta.requiresAuth && !user.value) {
next('/login')
} else if (to.meta.roles && !hasAnyRole(to.meta.roles)) {
next('/unauthorized')
} else {
next()
}
})
// Route definition
const routes = [
{
path: '/admin',
component: AdminPanel,
meta: { requiresAuth: true, roles: ['admin', 'superuser'] }
},
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true, roles: ['user', 'admin'] }
}
]
This code creates a comprehensive role-based authentication system using Vue 3’s Composition API with a reusable composable for auth logic and route guards for access control. The system checks user roles against route requirements, redirecting unauthorized users appropriately. The composable provides methods for role checking that can be used throughout components, while the router guard ensures route-level security before navigation occurs.
Best Practice Note:
This is the role-based authentication pattern we use in CoreUI Pro dashboard applications for enterprise-grade security. Consider implementing role hierarchies and caching user roles to optimize performance while maintaining security throughout your application.



