본문 바로가기
Angular.js

Angular Guard에 대하여

by 갈잃자 2023. 5. 30.

Angular에서 Guard란..

  • 라우팅 시점에서 실행되는 중간 역할을 하는 기능
  • 특정 조건을 검사하여 사용자가 특정 라우트로 진입할 수 있는지 없는지를 결정함
  • ex) 사용자의 권한, 인증상태, 데이터 로딩 등

Guard 사용법

1. Guard 클래스 생성 ng generate guard {guard-name}

ng generate guard {guard-name}

2. CanActivate 인터페이스 구현

  • CanActivate 메서드는 라우팅을 허용할 지 여부를 결정하는 논리를 작성하는 곳

3. Guard 등록

  • Guard 클래스를 모듈에 등록하고, Guard 클래스를 사용하려는 라우터 또는 라우터 그룹에 등록해야 함. 일반적으로 RouterModule.forRoot() 또는 RouterModule.forChild() 메서드에 Guard클래스를 등록

예시

1. ng generate guard auth 명령어를 이용하여 `AuthGuard` 란 클래스 생성

 

2. AuthGuard 클래스 내에 `CanActivate` 인터페이스를 구현 하고, canActivate 메서드를 작성하여 인증상태를 확인하는 논리 구현

// AuthGuard 내 코드
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      // 인증 상태 확인 로직 구현
      const isAuthenticated = /* 인증 상태 확인 로직 */;
      
      if (isAuthenticated) {
        return true; // 인증된 사용자는 해당 라우트로 진입 가능
      } else {
        this.router.navigate(['/login']); // 로그인 페이지로 리다이렉트
        return false; // 인증되지 않은 사용자는 해당 라우트로 진입 불가
      }
  }
}

3. 라우팅 모듈 파일에서 AuthGuard 를 등록

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  {
    path: 'dashboard',
    canActivate: [AuthGuard], // Guard 등록
    loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule)
  },
  //...
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Guard를 구현하고 등록하면, 해당 Guard가 라우팅을 제어하고, 권한이나 인증상태를 검사한 뒤 조건에 따라 특정 라우트로 진입시키거나 리다이렉트를 할 수 있음.

댓글