angularjwtnebularngx-admin

how to include auth token on header everytime http request send?


I use ngx-admin latest version, I have modify my app.module.ts like this:

    NbAuthModule.forRoot({
  strategies: [
    NbPasswordAuthStrategy.setup({
      name: 'email',
      baseEndpoint: 'https://localhost:5001',
      token: {
        class: NbAuthJWTToken,
        key: 'token'
       },
       login: {
         // ...
         endpoint: '/api/Auth/login',
         redirect: {
          success: '/pages/dashboard',
          failure: null, // stay on the same page
        },
       },
       logout:{
        redirect: {
          success: '/auth/login',
          failure: null, // stay on the same page
        },
       },
       register: {
         // ...
         endpoint: '/api/Auth/register',
       },
    }),
  ],
  forms: {
    login: formSetting,
       register: formSetting,
       requestPassword: formSetting,
       resetPassword: formSetting,
       logout: {
         redirectDelay: 0,
       },
  },
}), 

],

  bootstrap: [AppComponent],
  providers: [AuthGuard,
    { provide: HTTP_INTERCEPTORS, useClass: NbAuthJWTInterceptor, multi: true },]

I can do login and logout from my system and I got token saved into my localstorage with name app_auth_token and its contain:

{"name":"nb:auth:jwt:token","ownerStrategyName":"email","createdAt":1621867077000,"value":"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiJhZG1pbkBteWNhZmUuY29tIiwidW5pcXVlX25hbWUiOiJhZG1pbiIsInJvbGUiOiJBZG1pbiIsIm5iZiI6MTYyMTg2NzA3NywiZXhwIjoxNjIyMDM5ODc3LCJpYXQiOjE2MjE4NjcwNzd9.C06e6bSPhlIl16A3iTtU3yGi8078K1I5aTy-QDVIiX_cHr6-HQQAFjgQRwWuI9tuzCe5G9HC7IFSeyN_dI4BuA"}

I test on my page to retrieve data from server which is require auth, but it seem the header that sent to server has no token in it.

this.httpClient.get<User[]>(this.apiUrl+'user/list');

here is the header that I copy from browser

GET /api/user/list HTTP/2
Host: localhost:5001
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,id;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate, br
Origin: http://localhost:4200
DNT: 1
Connection: keep-alive
Referer: http://localhost:4200/
Pragma: no-cache
Cache-Control: no-cache

I recieve code 401 UnAuthorized

I test the token value in postman, it is valid and worked. but how to tell nebular to send the token everytime I did http request ? I read the doc it should be done automatically. did I miss something ?


Solution

  • Found the solution:

    in app.module.js I need to return false on NB_AUTH_TOKEN_INTERCEPTOR_FILTER

    I wish they put this on the docs

      providers: [AuthGuard,
        { provide: NB_AUTH_TOKEN_INTERCEPTOR_FILTER, useValue: function () { return false; }, },
        { provide: HTTP_INTERCEPTORS, useClass: NbAuthJWTInterceptor, multi: true },]