简体   繁体   English

在从 authGuard 的 canActivate 接收到 false 时进行路由器重定向

[英]Making router redirect upon receiving false from authGuard's canActivate

I have multiple authentication guards setup and use them in canActivate.我设置了多个身份验证防护并在 canActivate 中使用它们。 Normally I have had router.navigate(["/error",403]) in guard itself, but I have started combining different guards so for example i have guard A and guard B in some component i use A some use B and som use logical A OR B. this makes routing from inside guard unusable, when guard returns false routing doesn't do anything.通常我有router.navigate(["/error",403])在守卫本身,但我已经开始组合不同的守卫所以例如我在某些组件中有守卫 A 和守卫 B 我使用 A 一些使用 B 和一些使用逻辑 A 或 B。这使得来自守卫内部的路由无法使用,当守卫返回错误路由时,路由不会做任何事情。 Can I make angular router redirect to my /error/403 page upon returning false from my guards?从我的守卫返回 false 后,我可以让 Angular 路由器重定向到我的/error/403页面吗? I've heard that setting up wildcard to 403 works but I haven't seen any change after setting it up.我听说将通配符设置为 403 有效,但设置后我没有看到任何变化。 From what it seems if guard returns false angular doesn't do anything, i don't get any console message and page doesn't redirect anywhere.从看起来如果guard返回false angular不会做任何事情,我没有收到任何控制台消息并且页面不会重定向到任何地方。 How can I change this behaviour?我怎样才能改变这种行为?

canActivate can return, besides true / false , an UrlTree : canActivate可以返回,除了true / false ,一个UrlTree

  constructor(private router: Router) {}

  canActivate(snapshot: ActivatedRouteSnapshot): boolean | UrlTree {
    return someTest(snapshot) ? true : this.router.createUrlTree(['/', 'error', '403']);
  }

You can always extend your guards and return an UrlTree .你总是可以扩展你的守卫并返回一个UrlTree So any shared logic goes in your abstract class:因此,任何共享逻辑都在您的抽象类中:

export class GuardA extends Guard403 implements CanActivate {
  contructor(router: Router) {
    super(router);
  }

  canActivate(): Observable<boolean | UrlTree> {
    return this.canThisReallyActivateA().pipe(
      map((canActivate) => canActivate || this.cantActivate;
    )
  }
}

export class GuardB extends Guard403 implements CanActivate {
  contructor(router: Router) {
    super(router);
  }

  canActivate(): Observable<boolean | UrlTree> {
    return this.canThisReallyActivateB().pipe(
      map((canActivate) => canActivate || this.cantActivate;
    )
  }
}

export abstract class Guard403 {
  readonly cantActivate = this.router.createUrlTree(['/errror', '403']);

  constructor(protected router: Router) {}
}

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

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