Rest Angular 2身份验证与SPA的web api

Rest Angular 2身份验证与SPA的web api,rest,angular,authentication,django-rest-framework,Rest,Angular,Authentication,Django Rest Framework,为angular 2 SPA创建身份验证系统的最佳实践是什么。是否有任何内置的Angular2模块来处理此问题?您需要的核心是一个防护装置,以防止路由到需要身份验证的页面。Thoughtram和Jason Watmore展示了一个使用guard和JSON Web令牌的完整身份验证机制 无论您使用JWT(并且有理由不使用)还是会话(并且有理由不使用),这一切都取决于防范 你写了一个这样的守卫: @Injectable() export class AuthGuard implements CanA

为angular 2 SPA创建身份验证系统的最佳实践是什么。是否有任何内置的Angular2模块来处理此问题?

您需要的核心是一个防护装置,以防止路由到需要身份验证的页面。Thoughtram和Jason Watmore展示了一个使用guard和JSON Web令牌的完整身份验证机制

无论您使用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: '' }
];

不使用JWT和Seesions的原因是什么?最好的选择是什么?我这样问是因为我在API中使用django rest框架,而官方文档建议在SPA中使用seesions@user2080105 JWT和sessions都有自己的批评者。我认为关于会话的主要抱怨是必须维护服务器上的状态。JWT使会话很难或不可能在设定的时间之前过期。我没有做出任何判断,只是指出两者都有缺点。无论如何,这个解决方案对两者都有效。