프론트 개발 실무에서 로그인 회원가입 만들때 authGuard를 사용하시나요?
Angular에서 AuthGuard는 사용자 인증 및 권한 부여를 기반으로 경로에 대한 액세스를 제어하는 일반적인 메커니즘입니다. AuthGuard 자체는 로그인 또는 등록 기능을 직접 처리하지 않지만 인증되지 않은 액세스 또는 무단 액세스로부터 특정 경로를 보호하기 위해 이러한 기능과 함께 사용되는 경우가 많습니다.
다음은 Angular에서 AuthGuard를 설정하는 방법에 대한 간략한 개요입니다.
1.AuthGuard 서비스 만들기:
경로 활성화 또는 지연 로드 경로를 각각 보호할지 여부에 따라 CanActivate 또는 CanLoad 인터페이스를 구현하는 AuthGuard 서비스를 만듭니다.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
// Here, you'd typically check some authentication service or token
// For simplicity, let's assume we're checking a boolean flag
if (/* user is authenticated */) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
2.라우팅 구성에서 AuthGuard 사용:
AuthGuard 서비스가 정의되면 라우팅 구성에서 이를 사용하여 특정 경로를 보호할 수 있습니다.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{ path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] },
// ... other routes
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
3.실제 인증 메커니즘과 통합:
위의 예는 매우 단순화되었습니다. 실제 애플리케이션에서 AuthGuard는 인증 토큰의 존재와 유효성을 확인하는 인증 서비스 또는 사용자가 인증되었는지 여부를 결정하는 다른 메커니즘과 통합될 가능성이 높습니다.
4.역할 기반 액세스 제어(RBAC) 처리:
서로 다른 사용자가 서로 다른 역할을 갖고 있는 경우 AuthGuard 메커니즘을 확장하여 사용자가 인증되었는지 여부뿐만 아니라 특정 경로에 액세스하는 데 필요한 권한이나 역할이 있는지도 확인할 수 있습니다.
결론적으로 AuthGuard는 로그인 또는 등록 프로세스를 직접적으로 담당하지는 않지만 인증된(그리고 권한이 있는) 사용자만 Angular 애플리케이션의 특정 경로에 액세스할 수 있도록 하는 데 필수적인 역할을 합니다