首页 > 解决方案 > 请求堆栈未在 Angular 拦截器中发送新 cookie

问题描述

我正在尝试创建一个 HttpInterceptor 来管理会话到期时的 cookie 刷新。会话已成功更新,但堆栈中的一个请求未发送login()方法中收到的新 cookie。我找不到任何方法将新 cookie 共享到下一个请求中。

这里是如何执行请求的:

  1. 发布/警报状态:401
  2. 获取/状态?状态=关闭状态:401
  3. POST /login STATUS:200 <- 新 cookie
  4. 获取 /status?status=close 状态:401 -> 旧 cookie
  5. POST /alert STATUS: 200 <- 新 cookie

在此处输入图像描述

这是我的拦截器:

private isRefreshing = false;
    private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);

    constructor(@Inject(PLATFORM_ID) private platformId: Object,
                    private injector: Injector,
                    private authService: AuthenticationService) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<Object>> {
        let authReq = this.addTokenHeader(req);

        return next.handle(authReq).pipe(catchError(error => {
        if (error instanceof HttpErrorResponse && authReq.url.includes(environment.apiUrl) && !authReq.url.includes('login') && error.status === 401) {
            return this.handle401Error(authReq, next);
        }

        return throwError(error);
        }));
    }

    private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
        if (!this.isRefreshing) {
        this.isRefreshing = true;
        this.refreshTokenSubject.next(null);

        return this.authService.login(false).pipe(
            switchMap((response: any) => {
            this.isRefreshing = false;

            this.refreshTokenSubject.next(response);
            
            return next.handle(this.addTokenHeader(request));
            }),
            catchError((err) => {
            this.isRefreshing = false;
            
            this.authService.logout();
            return throwError(err);
            })
        );
            
        }

        return this.refreshTokenSubject.pipe(
        take(1),
        switchMap((token) => next.handle(this.addTokenHeader(request)))
        );
    }

    private addTokenHeader(request: HttpRequest<any>) {
        console.log(request.)
        return request.clone({ withCredentials: true });
    }

我怎样才能等到浏览器为下一个请求保存新的 cookie?

标签: angularhttprequestangular-http-interceptorshttpinterceptor

解决方案


推荐阅读