繁体   English   中英

Angular2中的AuthService

[英]AuthService in Angular2

我目前正在用angular2构建应用程序。 因此,我实现了一个用于处理登录,注册等的AuthService。如果在id_token(angular2-jwt)中签名的用户存储在localStorage中。 用户的角色和权限存储在AuthService.userRolesAuthService.userPerms

布尔属性AuthService.isAuthenticated使用angular2-jwt中的功能tokenNotExpired() ,如果用户已注销或本地存储中存储的令牌过期,则返回false。 如果将登录AuthService.isAuthenticated的用户更新为true

我得到了使用AuthGuard的路由,该路由仅允许通过身份验证的用户通过检查AuthService.isAuthenticated属性来激活此路由。

如果某条路线如下所示:

{
  path: "somewhere",
  component: SomeComponent,
  canActivate: [AuthGuard],
  data: {
    permissions: [
      "add:some",
      "edit:some"
    ]
  }
}

相同的AuthGuard通过将AuthService.userPerms与路由的data.permissions匹配来检查当前登录的用户是否具有所需的权限。 哪个也可以。

我的应用程序使用“主要组件”。 这主要成分是“公”, 使用AuthGuard。 它在主app.module内部引导, 没有自己的路由 在这个主要父组件的模板内部,我得到了应用程序范围的导航。

在此导航的内部是路由的按钮,这些按钮受AuthGuard保护,因此仅当用户登录且具有特定权限或角色(如果该路由需要)时才可以访问。 例如

<button [routerLink]="/somewhere">Somewhere</button>

如果用户单击此按钮且未获得授权,则将其重定向到unauthorized路由。 到目前为止工作

我想通过仅在用户能够激活路线的情况下使这些按钮可见来防止出现这种情况

<button [routerLink]="/somewhere"
  *ngIf="isAuthorized["buttonSomewhere"]">
  Somewhere
</button>

因此,在主AppComponent(处理导航)内部,我想检查模板内每个按钮的userPermissions并将结果存储在这样的对象中:

/* AppComponent */
public isAuthorized = {
   buttonSomewhere = true;
}

此项检查AuthService.isAuthorized(theRouteToBeActivated)处理,该方法在AppComponent构造函数内部调用,并将路由data.permissionAuthService.userPerms存储的用户权限进行AuthService.userPerms

问题是,由于AppComponent是公共的,并且不受AuthGuard保护,因此构造函数在用户未登录时运行,这是正确的。 此时,被调用的AuthService.isAuthorized(theRouteToBeActivated)返回false并将值存储在

/* AppComponent */
public isAuthorized = {
  buttonSomewhere = false;
}

这也是正确的。 因此,如果用户退出,他将看不到无法激活的路由按钮。

但是问题是:在用户登录了AppComponents构造函数中调用的AuthService.isAuthorized(theRouteToBeActivated)之后, 不会再次调用它,并且

/* AppComponent */
public isAuthorized = {
  buttonSomewhere = false;
}

保持原样。 但是在用户登录后,需要再次调用该函数,以便该函数返回true并进行更改

/* AppComponent */
public isAuthorized = {
  buttonSomewhere = true;
}

这样, 登录用户即可看到模板中的按钮。 目前,我需要在浏览器中重新加载应用程序。 然后,登录用户可以看到这些按钮。 但是我不想重新加载。

我该如何解决?

您可以通过在route参数中使用授权的防护来实现。 认证和授权之间是有区别的。 检查以下链接。

https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM