Solvedngx admin Add JWT automatically for every HTTP request

Is it possible to add a 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.

Any help is appreciated!

33 Answers

✔️Accepted Answer

FYI if you are using this solution check out my other reply:
#1375 (comment)

I couldn't get this to work, I added

      provide: HTTP_INTERCEPTORS,
      useClass: NbAuthJWTInterceptor,
      multi: true

to my app.module.ts but it still didn't add the Authorization header.

After some time I figured out that it was because of the NB_AUTH_TOKEN_INTERCEPTOR_FILTER which always returned true.

By default it is set in the auth.module.js:
{ provide: NB_AUTH_TOKEN_INTERCEPTOR_FILTER, useValue: nbNoOpInterceptorFilter },

And that function returns true:
export function nbNoOpInterceptorFilter(req) { return true; }

Not sure if I did something wrong or that this is a flaw, nevertheless: I fixed it by setting my own NB_AUTH_TOKEN_INTERCEPTOR_FILTER value which always returns false:

{ provide: NB_AUTH_TOKEN_INTERCEPTOR_FILTER, useValue: function () { return false; }, },

Thanks to this the header will be set by the NbAuthJWTInterceptor as so:

if (!this.filter(req)) {
            return this.authService.isAuthenticatedOrRefresh()

Other Answers:

For the people who encountered the same problem as me when the token is expired..
My solution results in a loop when the token is expired and the

if (!this.filter(req)) { return this.authService.isAuthenticatedOrRefresh()

calls the refresh API endpoint.

For an explanation check this issue: akveo/nebular#677
The solution is to add the refreshToken endpoint to the filter:

      useValue: function (req: HttpRequest<any>) {
        if (req.url === '/api/auth/refresh-token') {
          return true;
        return false;

@WerVbn or even simpler you can just inject the built-in Nebular interceptor the way @codex-corp described. We will add it to the documentation some time soon

I added the same code suggested by @codex-corp and I don't see the token being passed.
Can you please help?

providers: [ AuthGuard, { provide: APP_BASE_HREF, useValue: '/' }, { provide: NB_AUTH_TOKEN_WRAPPER_TOKEN, useClass: NbAuthJWTToken }, { provide: HTTP_INTERCEPTORS, useClass: NbAuthJWTInterceptor, multi: true}, ],


{ provide: NB_AUTH_TOKEN_INTERCEPTOR_FILTER, useValue: function () { return false; }, },
I get this error when I complete the login:
RangeError: Maximum call stack size exceeded

Any help please?

More Issues: