intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   const body = req.body;
   if (!body || !body.name ) {
     return next.handle(req);
   }
   // copy the body and trim whitespace from the name property
   const newBody = { ...body, name: body.name.trim() };
   // clone request and set its body
   const newReq = req.clone({ body: newBody });
   // send the cloned request to the next handler.
   return next.handle(newReq);
 }
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   if (req.headers.get('planner-req')) {
     const headers = new HttpHeaders({
       'Authorization' : `Bearer ${this.auth.getToken()}`,
       'Content-Type': `application/json`
     });
     const authreq = req.clone({
         headers: headers
     });
     return next.handle(authreq);
   }
   return next.handle(req);
 }
Example #3
0
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<any> {
        const token = this.tokenService.getToken();
        if (token) {
            console.log('token: ' + token);

            const authReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
            console.log('Authorization header: ' + authReq.headers.get('Authorization'));

            return next.handle(authReq);
        }

        return next.handle(req);
    }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let authRequest: any;

        if (this.shared.isLoggedIn()) {
            authRequest = req.clone({
                setHeaders: {
                    'Authorization': this.shared.token
                }
            });
            return next.handle(authRequest);
        } else {
            return next.handle(req);
        }
    }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (this.authService.isLoggedIn) {
      req = req.clone({
        setHeaders: {
          'Authorization': `Bearer ${this.authService.token}`
        }
      });

      return next.handle(req);
    }

    return next.handle(req);
  }
Example #6
0
 intercept(req: HttpRequest<any>,
           next: HttpHandler): Observable<HttpEvent<any>> {
     //debugger;
     const token = localStorage.getItem('token');
     if (token && !req.url.includes('maps.googleapis.com')) {
         const cloned = req.clone({
             headers: req.headers.set('jwt-token', token)
         });
         return next.handle(cloned);
     }
     else {
         return next.handle(req);
     }
 }
  /**
   * adds a header with a token
   *
   *
   * @param {HttpRequest<any>} request
   * @param {HttpHandler} next
   * @returns {Observable<HttpEvent<any>>}
   */
  intercept(request: HttpRequest<any>, next: HttpHandler) {

    const token = this.auth.getToken();
    if(token){
      const authReq = request.clone({
        headers: request.headers.set('x-auth',token)
      });
      return next.handle(authReq);

    }else{
      return next.handle(request);

    }

  }
Example #8
0
   intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
       if(request.method == 'GET') {
           return next.handle(request)
       } else {
           // Add CSRF headers for non GET requests
           const newHeaders: {[name: string]: string | string[]; } = {};
           for (const key of request.headers.keys()) {
               newHeaders[key] = request.headers.getAll(key);
           }          
           newHeaders['x-xsrf-token'] = OrcidCookie.getCookie('XSRF-TOKEN');           
           let _request = request.clone({headers: new HttpHeaders(newHeaders)});

           return next.handle(_request);
       }            
   }
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (!request || !request.url || (/^http/.test(request.url) && !(SERVER_API_URL && request.url.startsWith(SERVER_API_URL)))) {
            return next.handle(request);
        }

        const token = this.localStorage.retrieve('authenticationToken') || this.sessionStorage.retrieve('authenticationToken');
        if (!!token) {
            request = request.clone({
                setHeaders: {
                    Authorization: 'Bearer ' + token
                }
            });
        }
        return next.handle(request);
    }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.url.startsWith(environment.api)) {

      const token = this.oidcSecurityService.getToken();
      if (token !== '') {
        const tokenValue = 'Bearer ' + token;
        return next.handle(req.clone({
          setHeaders: {
            'Authorization': tokenValue
          }
        }));
      }
    }
    return next.handle(req);
  }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        let localUser = this.storage.getLocalUser();

        let N = API_CONFIG.baseUrl.length;
        let requestToAPI = req.url.substring(0, N) == API_CONFIG.baseUrl;

        if (localUser && requestToAPI) {
            const authReq = req.clone({headers: req.headers.set('Authorization', 'Bearer ' + localUser.token)});
            return next.handle(authReq);
        }
        else {
            return next.handle(req);
        }
    }
Example #12
0
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {

    // Clone the request to add the new header.
    // const authReq = req.clone({ headers: req.headers.set("headerName", "headerValue")});
    // console.log("Sending request with new header now ...");

    const authReq = req.clone({ withCredentials: true });

    return next.handle(authReq).pipe(
      tap(
        (event: HttpEvent<any>) => {
          if (event instanceof HttpResponse) {
            if (environment.production) {
              this.appInsightsService.trackEvent(req.url, req.body);
            }
          }
        },
        (err: any) => {
          if (err instanceof HttpErrorResponse) {
            if (err.status === 401 && req.url.toLocaleLowerCase().indexOf("auth/login") === -1) {
              window.location.href = environment.login_url;
            } else {
              if (environment.production) {
                this.appInsightsService.trackEvent(req.url, req.body);
              }
            }
          }
        }
      )
    );
  }
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            tap(
                (event: HttpEvent<any>) => {},
                (err: any) => {
                    if (err instanceof HttpErrorResponse) {
                        if (err.status === 401) {
                            const principal = this.injector.get(Principal);

                            if (principal.isAuthenticated()) {
                                principal.authenticate(null);
                                const loginModalService: LoginModalService = this.injector.get(LoginModalService);
                                loginModalService.open();
                            } else {
                                const loginService: LoginService = this.injector.get(LoginService);
                                loginService.logout();
                                const router = this.injector.get(Router);
                                router.navigate(['/']);
                            }
                        }
                    }
                }
            )
        );
    }
 // 拦截器 = request请求(pipe之前) + response返回(触发pipe,可以看头信息)
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     console.log('hello-interceptor:', req);
     // nexxt.handle进入下一个拦截器。不用next.handle返回一个Observable固定对象也行,express.js就是这么弄的
     return next.handle(req).pipe(
         tap(event => console.log('event:', event))
     );
 }
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const rh = this.tokenService.getRequestHeaders(req.body);
    const authReq = req.clone({
      headers: req.headers
        .set('style', rh.get('style').toString())
        .set('token', rh.get('token').toString())
        .set('validate', rh.get('validate').toString())
    });

    return next.handle(authReq).do(
      (event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          this.httpResponseSuccess(authReq, event);
        }
      },
      (err: any) => {
        if (err instanceof HttpErrorResponse) {
          this.httpResponseError(authReq, err);
        }
      }
    );
  }
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler,
  ): Observable<
  | HttpSentEvent
  | HttpHeaderResponse
  | HttpProgressEvent
  | HttpResponse<any>
  | HttpUserEvent<any>
  > {
    // 统一加上服务端前缀
    let url = req.url;
    if (!url.startsWith('https://') && !url.startsWith('http://')) {
      url = environment.SERVER_URL + url;
    }

    const newReq = req.clone({
      url: url,
    });
    return next.handle(newReq).pipe(
      mergeMap((event: any) => {
        if (event instanceof HttpResponse && event.status === 200)
          return this.handleData(event);
        return of(event);
      }),
      catchError((err: HttpErrorResponse) => this.handleData(err)),
    );
  }
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   const token: string = this._auth.token;
   if (token) {
     req = req.clone({
       setHeaders: {
         Authorization: `Bearer ${token}`,
         ContentType: 'application/json; charset=utf-8'
       }
     });
   } else {
     req = req.clone({
       setHeaders: {
         ContentType: 'application/json; charset=utf-8'
       }
     });
   }
   return next.handle(req).pipe(
     tap(
       (event: HttpEvent<any>) => {
         if (event instanceof HttpResponse) {
           // do stuff with response if you want
         }
       },
       (err: any) => {
         if (err instanceof HttpErrorResponse) {
           if (err.status === 401) {
             this._auth.collectFailedRequest(req);
             // console.log(err);
           }
         }
       }
     )
   );
 }
Example #18
0
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(catchError(error => {
            if (error instanceof HttpErrorResponse) {
                if ( error.status === 401 ) {
                    return throwError(error.statusText);
                }
                const applicationError = error.headers.get('Application-Error');
                if (applicationError) {
                    console.error(applicationError);
                    return throwError(applicationError);
                }

                const serverError = error.error;
                let modelStsteError = '';
                if (serverError && typeof serverError === 'object') {
                    for (const key in serverError) {
                        if (serverError[key]) {
                            modelStsteError += serverError[key] + '\n';
                        }
                    }
                    return throwError(modelStsteError || serverError || 'Server Error');
                }
            }
        }));
    }
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   return next.handle(req).pipe(tap(event => {
     if (event instanceof HttpResponse) {
       this.transferState.set(this.stateKey(req.url), event.body);
     }
   }));
 }
Example #20
0
 intercept(req: HttpRequest<any>, next: HttpHandler) {
   const authToken = this.authServive.fetchToken();
   const authReq = req.clone({
     headers: req.headers.set('Authorization', authToken)
   });
   return next.handle(authReq);
 }
Example #21
0
 intercept(req: HttpRequest<any>, next: HttpHandler) {
   const authToken = this.authService.getToken();
   const authRequest = req.clone({
     headers: req.headers.set('Authorization', 'Bearer ' + authToken)
   });
   return next.handle(authRequest);
 }
Example #22
0
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (!this.auth) {
      this.auth = this.injector.get(AuthService);
    }

    if (this.auth.isAuthenticated()) {
      request = request.clone({
        setHeaders: {
          'X-Auth-Token': this.auth.getToken()
        }
      });
    }

    // Add CSRF token for the Play CSRF filter
    const token = this.cookieService.get('PLAY_CSRF_TOKEN');
    if (token) {
      // Play looks for a token with the name Csrf-Token
      // https://www.playframework.com/documentation/2.4.x/ScalaCsrf
      request = request.clone({
        setHeaders: {
          'Csrf-Token': token
        }
      });
    }

    return next.handle(request);
  }
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   console.log('Intercepted!', req);
   // const copiedReq = req.clone({headers: req.headers.set('', '')});
   const copiedReq = req.clone({params: req.params.set('auth', this.authService.getToken())});
   return next.handle(copiedReq);
   // return null;
 }
Example #24
0
 /**
  * 拦截器  给请求设置 authorization 的头
  * @param {HttpRequest<any>} req
  * @param {HttpHandler} next
  * @description
  * @returns {Observable<HttpEvent<any>>}
  */
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   // 拦截请求
   let token = '43aaedb78c2ef89bb9ac1cd5f5f22ec'; // 获取token
   let authReq = null;
   if (token) {
     authReq = req.clone({setHeaders: {Authorization: token}});
   }
   if (req.url === '/business/topology/static/export') {
     authReq = authReq.clone({setHeaders: {'Content-Type': 'form-data'}});
   }
   return next.handle(authReq || req).pipe(mergeMap((event: any) => {
       if (event instanceof HttpResponse && event.status !== 200) {
         return Observable.create(observer => observer.next(event));
       }
       return Observable.create(observer => observer.next(event)); // 获取成功的
     }),
     catchError((err: HttpResponse<any>, caught: Observable<any>) => { // 返回异常
       if (err.status === 401) {
         this.confirmSrv.warning({
           nzTitle: '提示',
           nzContent: '登录超时,请重新登录!',
           nzOnOk: () => { }
         });
       }
       return Observable.create(observer => observer.next(event));
     })
   );
 }
Example #25
0
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   if (req.url.indexOf('/upload/file') === -1) {
     return next.handle(req);
   }
   const delay = 300; // Todo: inject delay?
   return createUploadEvents(delay);
 }
Example #26
0
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (!req.headers.has("Content-Type")) {
      req = req.clone({
        headers: req.headers.set("Content-Type", "application/json")
      });
    }

    req = req.clone({ headers: req.headers.set("Accept", "application/json") });

    if (this.auth.getToken() !== null) {
      req = req.clone({
        headers: req.headers.set("x-access-token", this.auth.getToken())
      });
    }

    return next.handle(req).do(evt => {
      if (evt instanceof HttpResponse) {
        console.log("---> status:", evt.status);
        console.log("---> filter:", req.params.get("filter"));
      }
    });
  }
 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     return next.handle(request).do(
         (event: HttpEvent<any>) => {
             if (event instanceof HttpResponse) {
                 const arr = event.headers.keys();
                 let alert = null;
                 let alertParams = null;
                 arr.forEach((entry) => {
                     if (entry.endsWith('app-alert')) {
                         alert = event.headers.get(entry);
                     } else if (entry.endsWith('app-params')) {
                         alertParams = event.headers.get(entry);
                     }
                 });
                 if (alert) {
                     if (typeof alert === 'string') {
                         if (this.alertService) {
                             const alertParam = alertParams;
                             this.alertService.success(alert, { param: alertParam }, null);
                         }
                     }
                 }
             }
         },
         (err: any) => {}
     );
 }
Example #28
0
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     const token = this.auth.getToken();
     const authReq = req.clone({
        headers: req.headers.set('Authorization', 'Bearer ' + token)
     });
     return next.handle(authReq);
 }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      tap(
        (event: HttpEvent<any>) => {},
        (err: any) => {
          if (err instanceof HttpErrorResponse) {
            if (err.status === 401 && err.url && !err.url.includes('/api/account')) {
              const destination = this.stateStorageService.getDestinationState();
              if (destination !== null) {
                const to = destination.destination;
                const toParams = destination.params;
                if (to.name === 'accessdenied') {
                  this.stateStorageService.storePreviousState(to.name, toParams);
                }
              } else {
                this.stateStorageService.storeUrl('/');
              }

              this.authServerProvider.logout();
              this.loginModalService.open();
            }
          }
        }
      )
    );
  }
Example #30
0
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const started = Date.now();
    let ok: string;

    // extend server response observable with logging
    return next.handle(req)
      .pipe(
        tap(
          // Succeeds when there is a response; ignore other events
          event => ok = event instanceof HttpResponse ? 'succeeded' : '',
          // Operation failed; error is an HttpErrorResponse
          error => ok = 'failed'
        ),
        // Log when response observable either completes or errors
        finalize(() => {
          const elapsed = Date.now() - started;
          const msg = `${req.method} "${req.urlWithParams}" ${ok} in ${elapsed} ms.`;
          if(ok == "failed"){
              this.logger.error(msg);
          }else{
              this.logger.trace(msg);
          }
        })
      );
  }