すべてのページで認証が必要な角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はここで認証チェックをしてはいけません。 –