CanActivate
CanActivate는 Angular의 라우트 가드 중 하나로, 사용자가 특정 경로로 이동하려고 할 때 해당 이동을 허용할지 여부를 결정합니다.
일반적으로 로그인 여부 확인, 사용자 권한 검사 등의 인증 및 인가 기능을 구현하는 데 사용됩니다.
사용 예시
- 로그인한 사용자만 대시보드 페이지 접근 가능하도록 제한
- 관리자 권한이 있는 사용자만 특정 페이지 접근 허용
- 특정 조건을 충족하지 않으면 로그인 페이지로 리디렉션
CanActivate 가드 구현
CanActivate 가드는 @Injectable() 데코레이터를 사용하여 서비스 형태로 구현됩니다.
1. AuthGuard 서비스 생성
먼저 AuthGuard 서비스를 생성합니다.
ng generate guard auth
- 생성된 auth.guard.ts 파일을 수정하여, 인증 여부를 확인하도록 구현합니다.
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
if (this.authService.isAuthenticated()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
2. AuthService 생성
AuthService를 사용하여 사용자의 로그인 여부를 확인합니다.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class AuthService {
private loggedIn = false;
isAuthenticated(): boolean {
return this.loggedIn;
}
login(): void {
this.loggedIn = true;
}
logout(): void {
this.loggedIn = false;
}
}
3. CanActivate 가드를 라우트에 적용하기
이제 app-routing.module.ts에서 CanActivate 가드를 특정 라우트에 적용합니다.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
{ path: '**', redirectTo: '/login' },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
- 이제 /dashboard 경로는 AuthGuard에 의해 보호되며, 인증되지 않은 사용자는 자동으로 /login 페이지로 이동됩니다.
CanActivate의 실행 흐름
- 사용자가 /dashboard 페이지로 이동을 시도함.
- CanActivate 가드가 실행되어 AuthService.isAuthenticated() 메서드 호출.
- 로그인 상태일 경우 true를 반환하여 페이지 접근을 허용.
- 로그인 상태가 아닐 경우 false를 반환하고 /login 페이지로 리디렉션.
관리자 권한 확인
관리자 권한을 가진 사용자만 특정 페이지에 접근하도록 설정할 수도 있습니다.
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean {
if (this.authService.isAuthenticated() && this.authService.isAdmin()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
- AuthService에서 관리자 여부를 확인하는 메서드를 추가해야 합니다.
isAdmin(): boolean {
// 예제: 관리자 계정인지 여부 확인
return this.loggedIn && localStorage.getItem('role') === 'admin';
}
'개발 공부 > Angular' 카테고리의 다른 글
| Angular Route Guard (canActivateChild, canDeactivate, canLoad ) (0) | 2025.03.17 |
|---|---|
| Angular Resolve (0) | 2025.03.15 |
| @ContentChild와 @ContentChildren 활용 (0) | 2025.02.21 |
| @ViewChild와 @ViewChildren (3) ngAfterViewInit, static (0) | 2025.02.17 |
| @ViewChild와 @ViewChildren (2) 기본 활용 (0) | 2025.02.15 |