授权与未经授权的主视图

时间:2017-01-10 14:14:48

标签: angular

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

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

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

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分: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阵列中。此外,您无需为警卫设置共享服务。