授权与未授权主视图 [英] Authorized vs unauthorized main view

查看:91
本文介绍了授权与未授权主视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

when my app is starting I check cookies and if user is authorized I want to show him MainComponent. If user is unauthorized LoginComponent needs to be shown.

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

Where this logic should be? In app.module.ts or in app.component.ts? How do I control which component will be shown? The logic "show MainComponent and then if user is unauthorized redirect to LoginComponent" isn't good, user wants to see proper component from start. How do I do that if root route is hardcoded in RouterModule?

谢谢. P.S.是的,我完全是Angular 2的新手:)

Thanks. P.S. Yes, I'm completely newbie in Angular 2 :)

推荐答案

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

Basically, you need a Guard to add to your Route.

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

You need to setup a Service that will store the authenticated status of your user (that is set when you login for example),

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

and then add a guard on your route which will check your service's boolean state, and allow the route to be activated or not. If the guard returns true, the user can access the route, if not you need to redirect him to your login and return false.

让我们很容易做到这一点:

Let's make that quite easily :

设置 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
]

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

Now, you are able to call your service from your component and set the authenticated state by calling your service using Dependency Injection :

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
    });
}


现在为您的路线添加一个警卫


And now add a guard to your route

设置 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:

Update your routes with the guard:

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

不要忘记将防护添加到appModule的提供程序中(请谨慎提供一次,因为您只需要一个防护实例即可).

Do not forget to add the guard to the providers of your appModule (And be careful to provide it once as you need only a single instance of your guard).

providers: [
    AuthGuard
]

注意:由于您还拥有一个非常小的应用程序,因此您可能将AuthGuard和服务都放在同一providers数组中.另外,您无需为警卫设置共享服务.

NB : Since you have a really tiny app yet, you will probably have both the AuthGuard and your service in the same providers array. Also, you don't need to setup a shared service for a guard.

这篇关于授权与未授权主视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆