question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

I want intercept all http request but, so far, only NbAuthService is intercepted

See original GitHub issue

Issue type

I’m submitting a …

  • bug report
  • feature request

Issue description

Current behavior:

When I throw a httpClient.post, for example, Intercerpt does not catch this request to add the Bearer Authentication

app.module.ts

providers: [
  { 
    provide: APP_BASE_HREF, 
    useValue: "/" 
  },
  AuthGuard,
  CredentialService,
  { 
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true
  },
  { 
    provide: HTTP_INTERCEPTORS,
    useClass: HttpClientInterception,
    multi: true
  },
@Injectable()
export class HttpClientInterception implements HttpInterceptor {
    constructor(private injector: Injector) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('intercetption ');
        console.log(this.authService.request);
        const modified = req.clone({ setHeaders: { 'Custom-Header-2': '2' } });
        return next.handle(modified);
    }
    protected get authService(): HttpClient {
        return this.injector.get(HttpClient);
    }
}

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    constructor(private injector: Injector,
        @Inject(NB_AUTH_INTERCEPTOR_HEADER) protected filter) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // do not intercept request whose urls are filtered by the injected filter
        console.log('dwdwd');
        if (!this.filter(req)) {
            return this.authService.isAuthenticatedOrRefresh()
                .pipe(
                    switchMap(authenticated => {
                        if (authenticated) {
                            return this.authService.getToken().pipe(
                                switchMap((token: NbAuthToken) => {
                                    const JWT = `Bearer ${token.getValue()}`;
                                    req = req.clone({
                                        setHeaders: {
                                            Authorization: JWT,
                                        },
                                    });
                                    return next.handle(req);
                                }),
                            )
                        } else {
                            // Request is sent to server without authentication so that the client code
                            // receives the 401/403 error and can act as desired ('session expired', redirect to login, aso)
                            return next.handle(req);
                        }
                    }),
                )
        } else {
            
            return next.handle(req);
        }
    }

    protected get authService(): NbAuthService {
        return this.injector.get(NbAuthService);
    }

}
import { ImeiSetup } from './../../../@shared/model/imei_setup.model';
import { ImeiAdapter } from './../../../@shared/model/imei.model';

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Imei } from '../../../@shared/model/imei.model';
import { CredentialService } from '../../../@shared/auth/login/credential.service';

@Injectable({
  providedIn: "root"
})
export class ImeiService {
  private apiRoot = 'http://<real-address-here>';
  constructor(private http: HttpClient, private imeiAdapter: ImeiAdapter, private userCredential: CredentialService,) {}

  projectName(): Observable<Imei> {
    //this request is not intercepted, so I need add Bearer manually
    return this.http
      .post(this.apiRoot.concat("kraken"), JSON.stringify({'option':'projects'})
      , {
        headers: new HttpHeaders({
          "Content-Type": "application/json",
          "Authorization": `Bearer ${this.userCredential.getTokenFromStorage()}`,
        })
      }
      )
      .map((data: any) => this.imeiAdapter.adapt(data));
  }

}

Expected behavior:

When

ImeiService.projectName()

be called, the internal http.post should trigged one of interceptor [TokenInterceptor or HttpClientInterception] and the should work, but non of them is trigged then I must add Bearer manually for each request that I am doing in my app (All request must send Bearer)

Steps to reproduce:

Intercepet NbAuthService, then try to intercept other http requests I already checked #1375 comments but does not work. Related code:

Other information:

npm, node, OS, Browser

npm: 6.4.1
node: v10.10.0
Linux: 18.04.2 LTS (Bionic Beaver)
Browser: Chrome/Firefox/

Angular, Nebular

"@nebular/auth": 3.1.0,
"@nebular/security": 3.4.0,
Angular CLI: 7.0.5
Node: 10.10.0
OS: linux x64
Angular: 7.0.3

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
anthowmcommented, Jun 13, 2019

Try to provide this in you pages.module.ts or in the lazy load module when you want to intercept ( anyways this is just for check if the problem is related to bad providers import).

0reactions
JosielManzonnicommented, Jun 24, 2019

@anthowm , putting in pages.module.ts worked.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to intercept all http requests including form submits
You can capture a form submit and insert an input into the form. As far as ajax requests go, global ajax events work...
Read more >
Intercept HTTP requests - Mozilla - MDN Web Docs
To intercept HTTP requests, use the webRequest API. This API enables you to add listeners for various stages of making an HTTP request....
Read more >
Intercepting Requests & Responses Using Axios
In general, an interceptor is nothing but a function that gets called for every single HTTP request made and the response received by...
Read more >
Intercepting JavaScript Fetch API requests and responses
In this article, you'll learn how to intercept JavaScript Fetch API calls. There are two types of events for which you may want...
Read more >
The Intercept Page - HTTP Toolkit
The page consists of a grid of clickable interception options, ... correctly configured but not appear in this list, if they haven't yet...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found