1

My objective:

I'm trying to implement authorization using JWT by sending the jwt token in the header with each request sent from the frontend. And I have addedd an interceptor for that.

The problem

The problem is that the front is always sending a request twice: the first one doesn't have the authorization : Beared .... in header while the second request does. Backend Logs after sending a request:

2020-07-02 18:07:43 INFO  JwtRequestFilter:45 - ============== Trying to access request URL  : 
/myaApp/rest/dummy-url
2020-07-02 18:07:43 INFO  JwtRequestFilter:47 - ============== Request Token Header : null
2020-07-02 18:07:46 INFO  JwtRequestFilter:45 - ============== Trying to access request URL  : 
/myaApp/rest/dummy-url
2020-07-02 18:07:46 INFO  JwtRequestFilter:47 - ============== Request Token Header : Bearer Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ6YWlyaSIsImV4cCI6MTU5MzcxMzA3MywiaWF0IjoxNTkzNzA5NDczLCJqdGkiOiIzIn0.BmNQlK8jFmDmYKeX6JSOu7HJfLwaA4ngvE09deKdOvZ1SpOScgGikJHnV27AaQNFyaJLwsxzhMxvZaXPC73jJQ

as a side note: When removing the interceptor, only one request is sent to the backend.

What I tried so far

After some research, I've been found that, the problem may be related to subscribing twice: in the interceptor and in the http service that get the data.So I used pipe.

import { Observable } from 'rxjs';
import {tap} from 'rxjs/internal/operators';
import { DataService } from './../sharedServices/data.service';
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse, HttpErrorResponse } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class JwtInterceptorService implements HttpInterceptor{
  constructor(private dataService : DataService) { }
  intercept(request : HttpRequest<any>, next:HttpHandler) : Observable<HttpEvent<any>>{
  let jwtToken = this.dataService.getJwtToken();

   let clonedReq = this.addToken(request, jwtToken);

   return next.handle(clonedReq).pipe(
   tap((event: HttpEvent<any>) => {
     console.log(event);
   }),
   tap((err: any) => {
      console.log(err);
   })
  );

 private addToken(request:HttpRequest<any>, jwtToken){
   if(jwtToken){
     let clone : HttpRequest<any>;
     clone = request.clone({
       setHeaders : {
         'Authorization': `Bearer ${jwtToken}`
       }
     });
     return clone;
   }
   return request;
 }
}

App.module

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
@NgModule({
...
 providers: [
             ...
             { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptorService, multi: true }
            ]
 ....
})

But that didnt fixed the problem..

PS: possible cause : I'm not sure about that, but I created the interceptor using ng g service since i couldnt generate a provider using my current angular version. Also to create an interceptor in Ionic 4 you have to use a service as they say in the official documentation.

Edit 1 : I did create the interceptor manually using touch src/app/interceptors/jwt-token.interceptor.ts but the problem persists.

Edit 2 : Even when I deleted entirely the interceptor, and added the header manually to my GET request, I still receive 2 requests in the back..

  public testHeader() {
    let headers: HttpHeaders = new HttpHeaders();
     headers = headers.append('Authorization', "a test token..");
     return this.http.get("http:localhost//myapp/rest/", {headers});
  } 
vgnsh
  • 120
  • 1
  • 15
Faouzi
  • 929
  • 2
  • 15
  • 23

0 Answers0