Example #1
0
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.headers.get('No-Auth') === 'True') {
        return next.handle(req.clone());
    }

    if (localStorage.getItem('currentUser') != null) {
        const clonedreq = req.clone({
            headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('currentUser'))
        });
        return next.handle(clonedreq)
            .do(
            succ => { },
            err => {
                if (err.status === 401) {
                    this.router.navigateByUrl('/login');
                }
            }
            );
    } else {
        this.router.navigateByUrl('/login');
    }
}
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${currentUser.token}`
                }
            });
        }

        return next.handle(request);
    }
Example #3
0
	intercept(req : HttpRequest <any>, next : HttpHandler) : Observable <HttpEvent<any>> {
			// Clone the request to add the new header
      const token = new TokenStorage();
      const tokenVal = token.getToken();
			const clonedRequest = req.clone({
			headers: req
				.headers
				.set('Authorization', tokenVal ? `Bearer ${ tokenVal}` : '')
		});

		// Pass the cloned request instead of the original request to the next handle
		return next.handle(clonedRequest);
	}
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        let currentUser = this.authenticationService.currentUserValue;
        if (currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: { 
                    Authorization: `Bearer ${currentUser.token}`
                }
            });
        }

        return next.handle(request);
    }
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // Add content-type for POST, PUT, PATCH automatically
        if (request.method === 'POST' || request.method === 'PUT' || request.method === 'PATCH') {
            request = request.clone({
                setHeaders: {
                    'Content-Type': 'application/json; charset=utf-8'
                }
            });
        }

        return next
            .handle(request)
            .catch(response => {
                let message: string;

                if (response instanceof HttpErrorResponse) {
                    switch (response.status) {
                        case 0: {
                            message = "No network connection";
                            break;
                        }
                        case 401: {
                            message = "Unauthenticated";
                            break;
                        }
                        case 403: {
                            message = "Unauthorized";
                            break;
                        }
                        case 404: {
                            message = "Resource Not Found";
                            break;
                        }
                        case 500: {
                            message = "Server error";
                            break;
                        }
                        default: {
                            message = response.status.toString();
                            break;
                        }
                    }
                }

                this.snackBar.open(message, null, {
                    duration: 2000
                });

                return Observable.throw(response);
            });
    }
 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

 request = request.clone({
    headers: new HttpHeaders(
      {
        'Content-Type':  'application/json',
        'Authorization': 'desafio-4-devs' 
      }
    )  
  });
  
 return next.handle(request);

 }
 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     return next.handle(request).do(
         (event: HttpEvent<any>) => {},
         (err: any) => {
             if (err instanceof HttpErrorResponse) {
                 if (!(err.status === 401 && (err.message === '' || (err.url && err.url.indexOf('/api/account') === 0)))) {
                     if (this.eventManager !== undefined) {
                         this.eventManager.broadcast({ name: 'jHipsterRegistryApp.httpError', content: err });
                     }
                 }
             }
         }
     );
 }
Example #8
0
 intercept(
     request: HttpRequest<any>,
     next: HttpHandler
 ): Observable<HttpEvent<any>> {
     const user: User = this.sessionStorage.retrieve('user');
     if (user && user.token) {
         request = request.clone({
             setHeaders: {
                 JWT: user.token,
             },
         });
     }
     return next.handle(request);
 }
 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) {
                         this.loginService.logout();
                     }
                 }
             }
         )
     );
 }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log(req.method);
        if (req.method == 'OPTIONS') {
            console.log("OPTIONS!");
        }
        console.log(req.body);
/*         if (req.url.startsWith("http://localhost:8080/")) {
            const newBody = this.toJsonString(req.body);
            const modified = req.clone({body: newBody});
            return next.handle(modified);
        } */
        console.log(req.url);
        return next.handle(req);
    }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpResponse<any>> {
    return next.handle(request).catch(error => {

      // we are only interested in HTTP 401 Unauthorized
      if (error.status === 401) {
        // our JWT is no longer valid, throw it away and show login
        this.authTokenProvider.removeToken();
        this.router.navigate(['/login']);
      }

      // different error occurred, rethrow it
      return Observable.throw(error);
    });
  }
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     // Clone the request to add the new header.
     const token = this.token.getToken();
     const tenantId = this.token.getTenantId();
     let authReq = req.clone();
     if (token) {
         authReq = req.clone({headers: req.headers.set('Authorization', 'Bearer ' + token)});
     }
     if (tenantId) {
         authReq = authReq.clone({headers: authReq.headers.set('X-TENANT-ID', tenantId)});
     }
     // Pass on the cloned request instead of the original request.
     return next.handle(authReq);
 }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        console.log('TimingInterceptor  intercepted');
        const started = Date.now();
        return next
            .handle(req)
            .do(event => {
                console.log('Dummy log');
                if (event instanceof HttpResponse) {
                    const elapsed = Date.now() - started;
                    console.log(`Request for ${req.urlWithParams} took ${elapsed} ms.`);
                }
            });
    }
 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.message === '' || (err.url && err.url.includes('/api/account'))))) {
                         this.eventManager.broadcast({ name: 'trebolApp.httpError', content: err });
                     }
                 }
             }
         )
     );
 }
Example #15
0
	intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
		const authService = this.injector.get(AuthService);

		let authToken = authService.getAuthToken();
		let authReq = req;

		if (authToken !== null)
			authReq = req.clone({headers: req.headers.set('Authorization', 'Bearer ' + authToken)});

		return next.handle(authReq).pipe(tap(() => {}, errorResponse => {
			if (errorResponse instanceof HttpErrorResponse && errorResponse.status == 401)
				this.router.navigate(['/login']);
		}));
	}
  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {

    this.authService = this.injector.get(AuthenticationService);

    if (!this.authService || !this.authService.getBearerExcludedUrls()) {
      return next.handle(req);
    }

    if (!this.excludedUrlsRegex) {
      this.loadExcludedUrlsRegex();
    }

    const urlRequest = req.url;
    const shallPass: boolean = !!this.excludedUrlsRegex.find((regex) => regex.test(urlRequest));
    if (shallPass) {
      return next.handle(req)
        .pipe(
          catchError((error) => {
            return observableThrowError(error);
          })
        );
    }

    return this.authService.addTokenToHeader(req.headers)
      .pipe(
        mergeMap((headersWithBearer) => {
        const kcReq = req.clone({ headers: headersWithBearer });
        return next.handle(kcReq)
          .pipe(
            catchError((error) => {
                return observableThrowError(error);
            })
          );
      })
      );
  }
 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   return next.handle(request).map((event: HttpEvent<any>) => {
     if (event.type === HttpEventType.Response) {
       if (event.body && event.body['_meta'] && event.body['_meta']['message']) {
         const meta = event.body['_meta'];
         this.notificationService.popNotification({
           type: meta['type'] ? NotificationType[meta['type']] as string : NotificationType.INFO,
           header: '',
           message: meta['message']
         });
       }
     }
     return event;
   });
 }
Example #18
0
 intercept(
   request: HttpRequest<any>,
   next: HttpHandler
 ): Observable<HttpEvent<any>> {
   let authToken = this.authService.idToken;
   if (request.url.includes('https://www.googleapis.com/youtube')) {
     authToken = this.authService.accessToken$.value;
   }
   request = request.clone({
     setHeaders: {
       Authorization: `Bearer ${authToken}`
     }
   });
   return next.handle(request);
 }
 intercept(request: HttpRequest<any>, next: HttpHandler):
   Observable<HttpEvent<any>> {
   return next.handle(request).pipe(
     tap(
       // success response
       event => {},
       // error response
       event => {
         if (event instanceof HttpErrorResponse) {
           this.notification.error(event.error.message);
         }
       }
     )
   );
 }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const jwt = this.authService.getToken()
    const authRequest = req.clone({ setHeaders: { authorization: `Bearer ${jwt}` } })
    return next.handle(authRequest).pipe(
      catchError((err, caught) => {
        if (err.status === 401) {
          this.router.navigate(['/user/login'], {
            queryParams: { redirectUrl: this.router.routerState.snapshot.url },
          })
        }

        return observableThrowError(err)
      })
    )
  }
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     
     const clonedreq = req.clone({
         withCredentials: true
     });
     
     return next.handle(clonedreq)
         .do(
             succ => { },
             err => {
                 if (err.status === 401 || err.status === 403)
                     this.router.navigateByUrl('/login');
             }
         );
 }
 /**
  * Intercept
  * @param req
  * @param next
  */
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   const key = `${new Date().getTime()}-${uuidv4()}`;
   this.httpLoaderService.add(key);
   return next.handle(req).pipe(
     map(event => {
       return event;
     }),
     catchError(error => {
       return throwError(error);
     }),
     finalize(() => {
       this.httpLoaderService.complete(key);
     })
   );
 }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token: string = localStorage.getItem('token');
    if (token) {
      // "Authorization : Bearer" format are most likely implementing OAuth 2.0 bearer tokens.
      request = request.clone({headers: request.headers.set('Authorization', 'Bearer ' + token)});
    }
    if (!request.headers.has('Content-Type')) {
      request = request.clone({headers: request.headers.set('Content-Type', 'application/json')});
    }
    request = request.clone({headers: request.headers.set('Accept', 'application/json')});
    console.log('%cHttpConfigInterceptor HttpRequest', 'color:yellow', request);

    // this deals with the response
    return next.handle(request).pipe(map(this.onSuccess), catchError(this.onError));
  }
Example #24
0
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   console.log('response service ');
   return next.handle(req).do((event: HttpEvent<any>) => {
     if (event instanceof HttpResponse) {
     }
   }, (err: any) => {
     if (err instanceof HttpErrorResponse) {
       if (err.status === 401) {
         console.log('error 401 ');
         this.authService.collectFailedRequests(req);
         this.router.navigate(['/login']);
       }
     }
   });
 }
  intercept(req: HttpRequest<any>,
            next: HttpHandler): Observable<HttpEvent<any>> {

    const idToken = localStorage.getItem("id_token");

    if (idToken) {
      const cloned = req.clone({
        headers: req.headers.set("Authorization",
          "Bearer " + idToken)
      });

      return next.handle(cloned);
    } else {
      return next.handle(req).pipe(catchError(err => {
        if (err.status === 401) {
          this.authService.logout();
          this.router.navigate(['/login'])
        }
        const error = err.error.message || err.statusText;
        return throwError(error);
      }));
    }

  }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const headersConfig = {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    };

    const token = this.jwtService.getToken();

    if (token) {
      headersConfig['Authorization'] = `Token ${token}`;
    }

    const request = req.clone({ setHeaders: headersConfig });
    return next.handle(request);
  }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // console.log(JSON.stringify(req));

        const token: string = this.currentUserService.token;

        if (token) {
            req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
        }

        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') });
        return next.handle(req);
    }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    let params = new HttpParams().append('token', this.trelloAuthService.getToken()).append('key', config.apiKey);

    // Copy old Params:
    request.params.keys().forEach(key => {
      params = params.set(key, request.params.get(key));
    });


    request = request.clone({
      params: params,
    });

    return next.handle(request);
  }
Example #29
0
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     const reqClone = req.clone({ withCredentials: true });
     return next
         .handle(reqClone)
         .pipe(
             tap(evt => {
                 if (evt instanceof HttpResponse) {
                     // console.log('---> status:', evt.status);
                 }
             }),
             catchError((err) => {
                 alert('ERROR \n' + JSON.stringify(err.error, null, 4));
                 return throwError(err);
             })
         );
 }
  public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // this.router.navigateByUrl('/login');

    // This clones the request to give the ability to add a new header
    // if we are using auth this is where we would put in our information on authentication to pass to the server

    const authReq = req.clone({ headers: req.headers.set('headerName', 'headerValue') });

    // send the newly created request

    return next.handle(authReq)
      .catch((error, caught) => {
        return Observable.throw(this.routeError(error));
      });
  }