Auth0 angular 7 登录重定向循环

Auth0 angular 7 login redirect loop

我正在使用 auth0 为我的 angular 7 应用配置授权。我按照快速入门指南起床 运行。除了 auth.service.ts 文件外,我唯一添加的是:

  getTokenSilently$(options?): Observable<string> {
    return this.auth0Client$.pipe(
      concatMap((client: Auth0Client) => from(client.getTokenSilently(options)))
    );
  }

支持 HTTP 拦截器:

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth.service';
import { Observable, throwError } from 'rxjs';
import { mergeMap, catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {

  constructor(private auth: AuthService) { }

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return this.auth.getTokenSilently$().pipe(
      mergeMap(token => {
        const tokenReq = req.clone({
          setHeaders: { Authorization: `Bearer ${token}` }
        });
        return next.handle(tokenReq);
      }),
      catchError(err => throwError(err))
    )
  }
}

我做的另一件事是我的应用程序没有登录按钮,当应用程序启动时,它会尝试转到具有授权保护的主页:

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, CanActivate } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import { tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean|UrlTree> | boolean {
    return this.auth.isAuthenticated$.pipe(
      tap(loggedIn => {
        if (!loggedIn) {
          this.auth.login(state.url);
        }
      })
    );
  }

}

所以它会自动调用登录,以便用户被重定向到 auth0。一旦他们输入了他们的信用,它就会将他们重定向回主页。然后突然间 auth.service.ts 服务再次加载并且 auth guard 再次触发并再次触发登录功能。这似乎一直在循环。

知道为什么它一直循环播放吗?

用这个替换你的 Guard 方法:

    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
    ): Observable<boolean> | Promise<boolean | UrlTree> | boolean {
        return this.auth.isAuthenticated$.pipe(
            delay(1000),
            tap(loggedIn => {
                if (!loggedIn) {
                    this.auth.login(state.url);
                }
            })
        );
    }

问题是 loggedIn 仍然在 false,即使在成功登录后也是如此。 我知道这不是一个干净或漂亮的解决方案。
我谦虚地认为 Auth0 Angular 示例需要一些修复。