티스토리 뷰
Angular의 view의 전환으로 사용하는 router가 있다.
그리고 이 view의 접근제어를 할 수 있는 기능이 있는데 라우터 가드(Router Guard)가 있다.
라우터 guard에는 다음과 같은 인터페이스 들이 있다.
CanActivate
to mediate navigation to a route.CanActivateChild
to mediate navigation to a child route.CanDeactivate
to mediate navigation away from the current route. # 라우터의 접근권한을 검사Resolve
to perform route data retrieval before route activation. # 라우터 변경시 호출되는 ㅂ라우트CanLoad
to mediate navigation to a feature module loaded asynchronously. #라우트 데이터를 가져와 컴포넌트에 제공
나도 다 사용해 보진 않았지만 로그인 구현이나 접근 제어를 하기위해 CanActivate를 이용해서 구현을 해보았다.
app.module.ts
{ path: 'mypage', loadChildren: './mypage/mypage.module#MypageModule', canActivate: [AuthLoginGuard], data: {roles: ['마이페이지'] }}
라우트를 정의할 때 canActivate를 이용해서 권한이 필요하다고 정의하고 data를 이용해 파라미터를 설정한다.
app.auth-login.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import { Globals } from '../app.globals';
@Injectable()
export class AuthLoginGuard implements CanActivate {
constructor(
private router: Router,
private globals: Globals
) { }
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable | Promise | boolean {
let roles = route.data["roles"] as string; // module에서 선언한 data: 밑의 roles 값을 받아온다.
if ( localStorage.getItem('login.token')) {
return true;
} else {
alert(roles +'는 로그인이 필요합니다.' + '\n로그인 창으로 이동합니다.');
// this.router.navigate(['/member/login']);
this.globals.link('/member/login', state.url);
return false;
}
}
}
이런식으로 선언해서 특정 url로 view를 접근할 때 canActivate로 인해서 이동하기전에 guard로 이동해 로직을 점검하고 이동할지 말지를 정한다.
이런식으로 비정상적인 루트를 통해 view에 접근하려는 것도 guard를 통해 제어할 수 있다.
Angular router guard에 관련된 자세한 내용은 공식 문서에 있다.
영알못이지만 그래도 최대한 원문을 이해하기 위해 노력하고 있다.
'FrontEnd > Angular' 카테고리의 다른 글
RouterEvent의 Navigation Detect (0) | 2018.07.18 |
---|---|
Angular 쿼리파람 (0) | 2018.07.16 |
양방향 바인딩 한글 짤리는 문제 (0) | 2018.07.10 |
Angular Security - Sanitization (0) | 2018.07.09 |
라우터 파라미터 (0) | 2018.07.04 |
- Total
- Today
- Yesterday
- JPA
- Redux
- data grid component
- JSON
- data component
- React-router
- https://www.tistory.com/auth/logout/
- Java
- localStorage
- python3
- Angular
- Spring
- 파이썬
- Spring Boot
- Python
- MySQL
- mobx
- Router
- data component module
- facebook login
- data table component
- 페이스북 로그인
- data gird component
- react
- 파이썬3
- angular router
- jQuery
- CSS
- JavaScript
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |