I have tried to pass JWT token in the header. I am using the below code. I have injected the auth service nad imported necessary files. But it's not working.
I want to add JWT to the HTTP header for every request? How can I achieve this? I need every request to be authenticated with an authorization token by my backend.
Angular app module code:
providers: [
AuthGuard,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
]
Angular interceptor code:
import { Inject, Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { switchMap } from 'rxjs/operators';
import { NbAuthJWTToken, NbAuthService, NB_AUTH_TOKEN_INTERCEPTOR_FILTER ,NbAuthToken} from '@nebular/auth';
/**
* TokenInterceptor
* @see https://angular.io/guide/http#intercepting-all-requests-or-responses
*/
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
private tokenService: NbAuthJWTToken;
constructor(private injector: Injector,
@Inject(NB_AUTH_TOKEN_INTERCEPTOR_FILTER) protected filter) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
debugger;
if (!this.filter(req)) {
return this.authService.isAuthenticatedOrRefresh()
.pipe(
switchMap(authenticated => {
if (authenticated) {
debugger;
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);
}
}
What I am doing wrong?