我有一個角度2應用程序,我需要在每個頁面上進行認證。所以我已經實現了一個自定義的RouterOutlet來確認我在每次頁面更改時都登錄了。Angular 2兒童路由認證
@Directive({
selector: 'auth-outlet'
})
export class AuthOutlet extends RouterOutlet {
publicRoutes: any;
private parentRouter: Router;
private authService: AuthService;
constructor(_elementRef: ElementRef,
_loader: DynamicComponentLoader,
_parentRouter: Router,
@Attribute('name') nameAttr: string,
_authService: AuthService) {
super(_elementRef, _loader, _parentRouter, nameAttr);
this.parentRouter = _parentRouter;
this.authService = _authService;
this.publicRoutes = {
'Login': true
};
}
activate(oldInstruction: ComponentInstruction) {
var url = this.parentRouter.lastNavigationAttempt;
console.log('attemping to nav');
if (!this.publicRoutes[url] && !this.authService.loggedIn){
var newInstruction = new ComponentInstruction('Login', [], new RouteData(), Login, false, 1);
return super.activate(newInstruction);
} else {
return super.activate(oldInstruction);
}
}
}
這裏是一個工作代碼: http://plnkr.co/edit/YnQv7Mh9Lxc0l0dgAo7B?p=preview
有沒有更好的辦法攔截路線的變化和重定向登錄時,用戶沒有通過驗證?
棒極了!你還需要什麼! – micronyks
那麼,有一件事你不應該新建一個ComponentInstruction。所以這已經有問題了。此外,如果您處於不瞭解登錄路線的兒童路線中,則會出現問題。 (我在海報上處理過這個問題) –
如果有人深入鏈接到頁面,那麼服務器就會參與進來,並且你在服務器上進行認證檢查。如果有人被授權,他們會進入您的應用程序。一旦進入你的應用程序,他們可以自由移動。瀏覽器和js不應該在這裏進行身份驗證檢查,服務器應該這樣做。 –