为angular 2 SPA创建身份验证系统的最佳做法是什么?是否有内置的Angular2模块来处理这个问题?
答案 0 :(得分:1)
您需要的核心是防止路由到需要身份验证的网页。虽然tram有一个great article on guards,但Jason Watmore a brilliant post显示了一个使用guard和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;
}
}
然后,无论您为app模块配置路由,都需要告知路由使用您的后卫:
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: '' }
];