为angular 2 SPA创建身份验证系统的最佳实践是什么?是否有任何内置的 Angular2 模块来处理这个问题?
您需要的核心内容是防止路由到需要身份验证的页面的防护。Thoughtram有一篇关于守卫的好文章,Jason Watmore有一篇精彩的文章,展示了使用守卫和JSON Web Tokens的完整身份验证机制。
无论您是使用 JWT(并且有理由不这样做)还是会话(并且有理由不这样做),这一切都归结为守卫。
你这样写一个守卫:
@Injectable()
export class AuthGuard implements CanActivate {
constructor (private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (isTheUserSignedIn()) {
return true;
}
// If not signed in, navigate to the login page and store the return URL
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
然后,无论在哪里为应用模块配置路由,都需要告诉路由使用防护:
const appRoutes: Routes = [
// Protect the Home route using the guard
{ path: '', component: HomeComponent, canActivate: [AuthGuard] },
// Don't protect the login and register pages
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
// Don't protect pages that don't need protecting
{ path: 'some-unprotected-page', component: UnprotectedPageComponent },
// Default redirect
{ path: '**', redirectTo: '' }
];