Search code examples
angularnebularngx-admin

NbAuthJWTToken is undefined after successful login


I am using ngx-admin with custom login. After successful login using API, control is redirecting to dashboard,but NbAuthJWTToken is undefined. When I refresh the page, page shows an error without reloading the page. How can I solve this? Please help me. NbAuthJWTToken Undefined Error on refreshing page

password-strategy-options.ts [auth/strategies/password/]

token?: NbPasswordStrategyToken = {
    class: NbAuthJWTToken,
    //class: NbAuthSimpleToken,
    key: 'data.token',
    getter: (module: string, res: HttpResponse<Object>, options: NbPasswordAuthStrategyOptions) => getDeepFromObject(
      res.body,
      options.token.key,
    ),
  };

auth-guard.service.ts [near app.module.ts]

export class AuthGuardService implements CanActivate {
  constructor(private authService: NbAuthService, private router: Router) {  }
  canActivate() {
    return this.authService.isAuthenticated()
      .pipe(
        tap(authenticated => {
          if (!authenticated) {
            this.router.navigate(['/login']);
          }
        }),
      );
  }
}

app.module.ts

@NgModule({
  declarations: [AppComponent],
  imports: [..........
    NbAuthModule,
    NbAuthModule.forRoot({
      strategies: [
        NbPasswordAuthStrategy.setup({
          name: 'email',
          baseEndpoint: 'api/',
          login: {
            endpoint: 'login',
          },
          token: {
            class: NbAuthJWTToken,
            key: 'token',
          }
        }),
      ],
      forms: {},
    }),
  ],
  bootstrap: [AppComponent],
  providers: [
    { provide: APP_BASE_HREF, useValue: '/' },
    AuthGuardService,
  ],
})

app-routing.module.ts

const routes: Routes = [
  { 
    path: 'pages', 
    canActivate: [AuthGuardService],
    loadChildren: 'app/pages/pages.module#PagesModule' 
  },
]

Solution

  • In ng-admin a successful login means that the server responded with a 100 http code. Aka with no error. So if you send an empty respond with no token it will still login. I believe that it can't find the token as you send it because it's not set right. Please share your res.