4

I'm using HttpInterceptor interface to add authorisation header on http petitions,

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(
        private localStorage: LocalStorageService,
        private sessionStorage: SessionStorageService
    ) {
    }

    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);
    }

}

my app module

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
      BrowserModule,
      AppRoutingModule,
      HttpClientModule,
      VistaModule,
      LayoutModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Locally it works perfectly but it fails when generates prod dist and uploads on server. Any petition obtains headers: Object, status: 401, statusText: "Unauthorized"

Can you help me?

3
  • Use your browser dev tools to check what the value in local storage is, what is sent in the request. Add logs to your server to see what it gets as token, what it expects. Commented Jun 10, 2018 at 16:08
  • I think it should be if(token) and not if(!token) ... Commented Jun 10, 2018 at 16:11
  • Do not clone request and assign it to same object reference. use something like const anotherReq=request.clone(); Commented Jun 10, 2018 at 17:31

1 Answer 1

2

Declare your Interceptor to be provided in root:

@Injectable({
    providedIn: 'root'
})

instead of using just:

@Injectable()

It means that your interceptor will be available in all your application, this in the case you have another module for product which could be the problem.

Check more details on: Angular Providers

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.