본문 바로가기
framework_library/vue

🚦 Vue Router - 네비게이션 가드와 인증 처리

by 죄니안죄니 2025. 5. 5.

🚦 Vue Router - 네비게이션 가드와 인증 처리

Vue 기초 시리즈 > 4️⃣ Vue Router > 네비게이션 가드와 인증 처리


1. 네비게이션 가드란?

Vue Router는 라우터 전환 시 원하는 조건을 검사하거나 리디렉션하는 가드(Guard)를 제공합니다. 인증 상태 확인, 권한 검사, 또는 저장되지 않은 변경사항 경고 등에 활용할 수 있습니다.

2. 전역 가드 (Global Navigation Guards)

router.beforeEach()를 이용해 모든 라우트 전환 전에 조건을 체크할 수 있습니다.

// main.js 또는 router/index.js
router.beforeEach((to, from, next) => {
  const isLoginRequired = to.meta.requiresAuth;
  const isAuthenticated = !!localStorage.getItem("token");

  if (isLoginRequired && !isAuthenticated) {
    next("/login"); // 로그인 안 되어 있으면 리다이렉트
  } else {
    next(); // 통과
  }
});
  • to: 이동하려는 라우트
  • from: 현재 라우트
  • next(): 다음 단계로 진행 (또는 특정 경로로 이동 가능)

3. 개별 라우트 가드

라우트 정의 시 beforeEnter 옵션을 사용하여 특정 라우트에만 가드를 적용할 수 있습니다.

{
  path: '/admin',
  component: AdminPage,
  beforeEnter: (to, from, next) => {
    const isAdmin = store.state.user.role === 'admin';
    if (!isAdmin) {
      alert("관리자만 접근 가능합니다.");
      next('/');
    } else {
      next();
    }
  }
}

4. 컴포넌트 내부 가드

컴포넌트 안에서도 라우트 변경 직전에 체크할 수 있는 beforeRouteLeave, beforeRouteEnter 등을 사용할 수 있습니다.

export default {
  beforeRouteLeave(to, from, next) {
    const answer = confirm("변경 사항이 저장되지 않았습니다. 정말 나가시겠습니까?");
    if (answer) {
      next();
    } else {
      next(false); // 이동 취소
    }
  }
};

5. 인증 처리 로직 실전 예제

1️⃣ 로그인 여부 확인 → 전역 가드

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("access_token");

  if (to.meta.requiresAuth && !token) {
    return next("/login");
  }

  next();
});

2️⃣ 라우트에 인증이 필요한지 설정

{
  path: "/dashboard",
  component: DashboardPage,
  meta: { requiresAuth: true }
}

3️⃣ 로그인 성공 시 토큰 저장

// 로그인 API 호출 후
localStorage.setItem("access_token", token);
router.push("/dashboard");

6. 실무 팁 및 주의사항

  • beforeEach 가드에는 반드시 next() 호출 필요 (안 하면 라우터 멈춤)
  • meta 필드는 사용자 정의 가능 → meta.requiresAuth, meta.roles
  • Vuex와 연동하여 사용자 상태/권한을 중앙에서 관리
  • 토큰이 만료되었는지 axios 인터셉터에서도 병행 체크 (중앙 인증 관리)

📌 다음 글 안내

👉 다음 글: 라우트 중첩과 Lazy Loading 적용하기

댓글