首页 文章

授权与未经授权的主视图

提问于
浏览
0

当我的应用程序启动时,我检查cookie,如果用户被授权,我想向他展示MainComponent . 如果用户未经授权,则需要显示LoginComponent .

这个逻辑应该在哪里?在app.module.ts或app.component.ts中?如何控制将显示哪个组件?逻辑“显示MainComponent然后如果用户未经授权重定向到LoginComponent”是不好的,用户希望从开始看到正确的组件 . 如果在RouterModule中对根路由进行硬编码,我该怎么做?

谢谢 . 附:是的,我在Angular 2中完全是新手:)

2 回答

  • 0

    基本上,您需要 Guard 添加到 Route .

    您需要设置一个 Service ,它将存储您的用户的身份验证状态(例如,在您登录时设置),

    然后在您的路线上添加一个 guard ,它将检查您的 service's boolean state ,并允许激活或不激活路线 . 如果守卫返回 true ,则用户可以访问该路由,如果不是,则需要将其重定向到 login 并返回false .


    让我们很容易做到:

    设置 auth.service.ts

    @Injectable()
    export class AuthService {
    
      public isAuthenticated: boolean = false;
    
      constructor(
         // Your DI needs
      ) { }
    
      // Sets the authenticated state
      setLoggedInState(): void {
        this.isAuthenticated = tokenNotExpired(); // I'm using angular2-jwt for token management
      }
    }
    

    不要忘记在 ngModule() 中添加服务提供商

    providers: [
      AuthService
    ]
    

    现在,您可以通过使用依赖注入调用服务从组件调用服务并设置身份验证状态:

    onSubmit() {
      // I set my authenticated state from the service itself after I got the Token
      this.authService.getToken(this.currentUser.email,   this.currentUser.password)
        .subscribe((token) => {
          this.router.navigate(['/dashboard']);  // Route that should be accessed upon login
        });
    }
    

    现在为你的路线添加一名警卫

    设置 auth.guard.ts

    @Injectable()
    export class AuthGuard implements CanActivate {
    
      constructor(private authService: AuthService, private router: Router) {
      }
    
      /**
       *  Protects the routes to reach with authentication
       */
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
        if (this.authService.isAuthenticated) {
          return true;
        } else {
          this.router.navigate(['/login']);
          return false;
        }
      }
    }
    

    用警卫更新你的 routes

    const routes: Routes = [
      { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
    ];
    

    不要忘记将警卫添加到 appModule 的提供者处(并且要小心提供一次,因为您只需要一个警卫实例) .

    providers: [
        AuthGuard
    ]
    

    注意:由于您的应用程序非常小,您可能会将AuthGuard和您的服务放在同一个 providers 阵列中 . 此外,您不需要为警卫设置共享服务 .

  • 0

    Roman,Angular 2为您提供了CanAtivate方法,可以使用您的路由列表配置,以说明用户是否可以访问特定路由 .

    基本上,您需要像这样配置您的路线

    import { AuthGuard } from './shared/auth-guard.service';
    const routes: Routes = [
        { path: 'settings', [...other configurations...], canActivate: [AuthGuard] }
       ...other routes...
      ]
    

    因此,每当您尝试访问应用程序的/ settings页面时,Angular会向AuthGuard询问您是否可以这样做 .

    以下是我对AuthGuard的完整实现(您可能需要进行一些更改):

    // Angular
    import { Injectable } from '@angular/core';
    import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, NavigationExtras } from '@angular/router';
    
    // Application
    import { Session } from './index';
    
    @Injectable()
    export class AuthGuard implements CanActivate {
    
        constructor(private session: Session, private router: Router) { }
    
        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
            if (this.session.hasValidAuthToken()) // check if the user can acess the route or not
                return true; // let the user to access the route
    
            let navigationExtras: NavigationExtras = {
                preserveQueryParams: false,
                queryParams: { url: state.url }
            };
    
            //if not, redirect to the login route
            this.router.navigate(['/login'], navigationExtras);
            return false;
        }
    }
    

相关问题