允许使用路由

时间:2018-04-30 07:30:33

标签: angular authorization angular2-routing

Angular 5

要求:用户应该只有在获得授权的情况下才能访问该页面。

注意:从服务器检索用户权限,从中将值提取到应用程序中。

当前实现:对于每个组件,在ngOnInit()方法中,我使用对服务器的HTTP请求检查用户是否已获得授权,之后我允许访问页面或使用Router.navigateByUrl导航到访问被拒绝的页面。

用户是否可以绕过此检查?这种方法有什么缺陷?

1 个答案:

答案 0 :(得分:3)

Angular的路由器CanActivate专门为此

制作

我的一个项目的摘录:

<强>路由

const routes: Routes = [
  { path: 'register', component: RegisterComponent, data: {reset:false} },
  { path: 'reset', component: RegisterComponent, data: {reset:true} },
  { path: 'registered/:email/:guid', component: RegisteredComponent },
  { path: 'login', component: LoginComponent },
  { path: 'cockpit', component: CockpitComponent, canActivate: [AuthGuardService] }, etc..

<强> AuthGuardService

import {Injectable} from '@angular/core';
import {CanActivate, Router} from "@angular/router";
import {AuthService} from "./auth.service";

@Injectable()
export class AuthGuardService implements CanActivate {

  constructor(private authService: AuthService,
              private router: Router) {}

  canActivate() {
    return this.authService.isLoggedIn().map(success => {
      if (success === false) {
        this.router.navigate(['login']);
      }
      return success;
    });
  }
}