akveo / nebular

:boom: Customizable Angular UI Library based on Eva Design System :new_moon_with_face::sparkles:Dark Mode
https://akveo.github.io/nebular
MIT License
8.05k stars 1.51k forks source link

Token expired right after login #2322

Open intankirana19 opened 4 years ago

intankirana19 commented 4 years ago

Issue type

I'm submitting a

Issue description

Sorry for I'm new with node.js, angular, nebular I'm not sure is it my API that's wrong or my client side I tested Login API in postman and put the token in every other api header and it works

For client side I use Nebular Authentication and Interceptors I can log in, there's token generated and page redirect to the after login page but all data I try to get from other api wont show because the status code 401 Unauthorized, I also try the token generated to postman also unauthorized.

What I possibly doing wrong? And why its 401 Unauthorized but I can still login and access the page that i already guard with AuthGuard

Current behavior: login api works image

but right after login, the api I need to access got unauthorized image

Expected behavior: The token after login authorized so it can access all API, if unauthorized stay in login page

Related code: Here's app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { CoreModule } from './@core/core.module';
import { ThemeModule } from './@theme/theme.module';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import {
  NbChatModule,
  NbDatepickerModule,
  NbDialogModule,
  NbMenuModule,
  NbSidebarModule,
  NbToastrModule,
  NbWindowModule,
} from '@nebular/theme';
import { AuthGuard } from './@core/services/auth-guard.service';
import { AsyncPipe, LocationStrategy, PathLocationStrategy, APP_BASE_HREF } from '@angular/common';
import { HttpTokenInterceptor } from 'app/@core/services/interceptors/http.token.interceptor';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    AppRoutingModule,

    ThemeModule.forRoot(),

    NbSidebarModule.forRoot(),
    NbMenuModule.forRoot(),
    NbDatepickerModule.forRoot(),
    NbDialogModule.forRoot(),
    NbWindowModule.forRoot(),
    NbToastrModule.forRoot(),
    NbChatModule.forRoot({
      messageGoogleMapKey: 'AIzaSyA_wNuCzia92MAmdLRzmqitRGvCF7wCZPY',
    }),
    CoreModule.forRoot(),
  ],
  bootstrap: [AppComponent],
  providers: [
    AuthGuard,
    {
      provide: LocationStrategy,
      useClass: PathLocationStrategy,
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpTokenInterceptor,
      multi: true
    },
    { provide: APP_BASE_HREF, useValue: '/' },

    // MessagingService, 
    AsyncPipe
  ],
})
export class AppModule {
}

Here's interceptor

import { NbAuthService, NB_AUTH_TOKEN_INTERCEPTOR_FILTER, NbAuthToken } from '@nebular/auth';
import { Injectable, Injector, Inject } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';

@Injectable()
export class HttpTokenInterceptor implements HttpInterceptor {

  constructor(private injector: Injector,
              @Inject(NB_AUTH_TOKEN_INTERCEPTOR_FILTER) protected filter) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // do not intercept request whose urls are filtered by the injected filter
    // if (!this.filter(req)) {
      return this.authService.isAuthenticatedOrRefresh()
        .pipe(
          switchMap(authenticated => {
            if (authenticated) {
                return this.authService.getToken().pipe(
                  switchMap((token: NbAuthToken) => {
                    const JWT = `${token.getValue()}`;
                    req = req.clone({
                      setHeaders: {
                        Authorization: JWT,
                      },
                    });
                    return next.handle(req);
                  }),
                );
            } else {
              return next.handle(req);
            }
          }),
        );
    // } else {
    //   return next.handle(req);
    // }
  }

  protected get authService(): NbAuthService {
    return this.injector.get(NbAuthService);
  }
}

Here's app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {
  NbAuthComponent, NbRegisterComponent,
  NbLogoutComponent, NbRequestPasswordComponent,
  NbResetPasswordComponent,
  NbLoginComponent
} from '@nebular/auth';
import { AuthGuard } from './@core/services/auth-guard.service';

const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    loadChildren: 'app/pages/pages.module#PagesModule'
  },
  {
    path: 'auth',
    component: NbAuthComponent,
    children: [
      {
        path: '',
        component: NbLoginComponent,
      },
      {
        path: 'login',
        component: NbLoginComponent,
      },
      {
        path: 'register',
        component: NbRegisterComponent,
      },
      {
        path: 'logout',
        component: NbLogoutComponent,
      },
      {
        path: 'request-password',
        component: NbRequestPasswordComponent,
      },
      {
        path: 'reset-password',
        component: NbResetPasswordComponent,
      },
    ],
  },
  { path: '', redirectTo: '', pathMatch: 'full' },
  { path: '**', redirectTo: '' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Here's auth guard

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { NbAuthService } from '@nebular/auth';
import { tap } from 'rxjs/operators';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: NbAuthService, private router: Router) {
  }

  canActivate() {
    return this.authService.isAuthenticated()
      .pipe(
        tap(authenticated => {
          if (!authenticated) {
            this.router.navigate(['auth/login']);
          }
        }),
      );
  }
}

Here's core.module.ts

import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core';
import { CommonModule } from '@angular/common';

import { NbSecurityModule, NbRoleProvider } from '@nebular/security';
import { of as observableOf } from 'rxjs';

import { throwIfAlreadyLoaded } from './module-import-guard';
import {
  AnalyticsService,
  LayoutService,
  PlayerService,
  SeoService,
  StateService,
} from './utils';
import { UserData } from './data/users';
import { ElectricityData } from './data/electricity';
import { SmartTableData } from './data/smart-table';
import { UserActivityData } from './data/user-activity';
import { OrdersChartData } from './data/orders-chart';
import { ProfitChartData } from './data/profit-chart';
import { TrafficListData } from './data/traffic-list';
import { EarningData } from './data/earning';
import { OrdersProfitChartData } from './data/orders-profit-chart';
import { TrafficBarData } from './data/traffic-bar';
import { ProfitBarAnimationChartData } from './data/profit-bar-animation-chart';
import { TemperatureHumidityData } from './data/temperature-humidity';
import { SolarData } from './data/solar';
import { TrafficChartData } from './data/traffic-chart';
import { StatsBarData } from './data/stats-bar';
import { CountryOrderData } from './data/country-order';
import { StatsProgressBarData } from './data/stats-progress-bar';
import { VisitorsAnalyticsData } from './data/visitors-analytics';
import { SecurityCamerasData } from './data/security-cameras';

import { UserService } from './mock/users.service';
import { ElectricityService } from './mock/electricity.service';
import { SmartTableService } from './mock/smart-table.service';
import { UserActivityService } from './mock/user-activity.service';
import { OrdersChartService } from './mock/orders-chart.service';
import { ProfitChartService } from './mock/profit-chart.service';
import { TrafficListService } from './mock/traffic-list.service';
import { EarningService } from './mock/earning.service';
import { OrdersProfitChartService } from './mock/orders-profit-chart.service';
import { TrafficBarService } from './mock/traffic-bar.service';
import { ProfitBarAnimationChartService } from './mock/profit-bar-animation-chart.service';
import { TemperatureHumidityService } from './mock/temperature-humidity.service';
import { SolarService } from './mock/solar.service';
import { TrafficChartService } from './mock/traffic-chart.service';
import { StatsBarService } from './mock/stats-bar.service';
import { CountryOrderService } from './mock/country-order.service';
import { StatsProgressBarService } from './mock/stats-progress-bar.service';
import { VisitorsAnalyticsService } from './mock/visitors-analytics.service';
import { SecurityCamerasService } from './mock/security-cameras.service';
import { MockDataModule } from './mock/mock-data.module';
import { environment } from '../../environments/environment';

import { NbAuthModule, 
  NbPasswordAuthStrategy, 
  NbAuthJWTToken, 
  NbTokenStorage, 
  NbTokenLocalStorage } from '@nebular/auth';

const DATA_SERVICES = [
  { provide: UserData, useClass: UserService },
  { provide: ElectricityData, useClass: ElectricityService },
  { provide: SmartTableData, useClass: SmartTableService },
  { provide: UserActivityData, useClass: UserActivityService },
  { provide: OrdersChartData, useClass: OrdersChartService },
  { provide: ProfitChartData, useClass: ProfitChartService },
  { provide: TrafficListData, useClass: TrafficListService },
  { provide: EarningData, useClass: EarningService },
  { provide: OrdersProfitChartData, useClass: OrdersProfitChartService },
  { provide: TrafficBarData, useClass: TrafficBarService },
  { provide: ProfitBarAnimationChartData, useClass: ProfitBarAnimationChartService },
  { provide: TemperatureHumidityData, useClass: TemperatureHumidityService },
  { provide: SolarData, useClass: SolarService },
  { provide: TrafficChartData, useClass: TrafficChartService },
  { provide: StatsBarData, useClass: StatsBarService },
  { provide: CountryOrderData, useClass: CountryOrderService },
  { provide: StatsProgressBarData, useClass: StatsProgressBarService },
  { provide: VisitorsAnalyticsData, useClass: VisitorsAnalyticsService },
  { provide: SecurityCamerasData, useClass: SecurityCamerasService },
];

export class NbSimpleRoleProvider extends NbRoleProvider {
  getRole() {
    return observableOf('guest');
  }
}

export const NB_CORE_PROVIDERS = [
  ...MockDataModule.forRoot().providers,
  ...DATA_SERVICES,
  ...NbAuthModule.forRoot({

    strategies: [
      NbPasswordAuthStrategy.setup({
        name: 'email',
        token: {
          class: NbAuthJWTToken,
          key: 'token', 
        },

        baseEndpoint: environment.apiUrl,
        login: {
          // ...
          endpoint: '/login',
          method: 'post',
          redirect: {
            success: 'pages/iot-dashboard',
            failure: null, // stay on the same page
          },
        },
        logout: {
          endpoint: '',
          method: 'post'
        },
      }),
    ],
    forms: {
      login: {
        redirectDelay: 500, 
        strategy: 'email', 
        rememberMe: false, 
        register: false,
        showMessages: {    
          success: true,
          error: true,
        },
      },
      logout: {
        redirectDelay: 500,
        strategy: 'email',
      },
      validation: {
        password: {
          required: true,
        },
        email: {
          required: true,
        },
      }
    },
  }).providers,

  { provide: NbTokenStorage, useClass: NbTokenLocalStorage },

  NbSecurityModule.forRoot({
    accessControl: {
      guest: {
        view: '*',
      },
      user: {
        parent: 'guest',
        create: '*',
        edit: '*',
        remove: '*',
      },
    },
  }).providers,

  {
    provide: NbRoleProvider, useClass: NbSimpleRoleProvider,
  },
  AnalyticsService,
  LayoutService,
  PlayerService,
  SeoService,
  StateService,
];

@NgModule({
  imports: [
    CommonModule,
  ],
  exports: [
    NbAuthModule,
  ],
  declarations: [],
})
export class CoreModule {
  constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
    throwIfAlreadyLoaded(parentModule, 'CoreModule');
  }

  static forRoot(): ModuleWithProviders {
    return <ModuleWithProviders>{
      ngModule: CoreModule,
      providers: [
        ...NB_CORE_PROVIDERS,
      ],
    };
  }
}

Other information:

npm, node, OS, Browser

<!--
Node: v12.14.1
NPM: 6.13.4
OS: Windows 10
Browser: Chrome
-->

Angular, Nebular

{
  "name": "ngx-admin",
  "version": "4.0.1",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/akveo/ngx-admin.git"
  },
  "bugs": {
    "url": "https://github.com/akveo/ngx-admin/issues"
  },
  "scripts": {
    "ng": "ng",
    "conventional-changelog": "conventional-changelog",
    "start": "ng serve",
    "build": "ng build",
    "build:prod": "npm run build -- --prod --aot",
    "test": "ng test",
    "test:coverage": "rimraf coverage && npm run test -- --code-coverage",
    "lint": "ng lint",
    "lint:fix": "ng lint ngx-admin-demo --fix",
    "lint:styles": "stylelint ./src/**/*.scss",
    "lint:ci": "npm run lint && npm run lint:styles",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "ng e2e",
    "docs": "compodoc -p src/tsconfig.app.json -d docs",
    "docs:serve": "compodoc -p src/tsconfig.app.json -d docs -s",
    "prepush": "npm run lint:ci",
    "release:changelog": "npm run conventional-changelog -- -p angular -i CHANGELOG.md -s"
  },
  "dependencies": {
    "@agm/core": "^1.0.0-beta.5",
    "@angular/animations": "^8.0.0",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "^8.0.0",
    "@angular/compiler": "^8.0.0",
    "@angular/core": "^8.0.0",
    "@angular/forms": "^8.0.0",
    "@angular/platform-browser": "^8.0.0",
    "@angular/platform-browser-dynamic": "^8.0.0",
    "@angular/router": "^8.0.0",
    "@asymmetrik/ngx-leaflet": "3.0.1",
    "@nebular/auth": "4.4.0",
    "@nebular/eva-icons": "4.4.0",
    "@nebular/security": "4.4.0",
    "@nebular/theme": "4.4.0",
    "@swimlane/ngx-charts": "^10.0.0",
    "angular-tree-component": "7.2.0",
    "angular2-chartjs": "0.4.1",
    "angular2-toaster": "^7.0.0",
    "bootstrap": "4.3.1",
    "chart.js": "2.7.1",
    "ckeditor": "4.7.3",
    "classlist.js": "1.1.20150312",
    "core-js": "2.5.1",
    "echarts": "^4.0.2",
    "eva-icons": "^1.1.0",
    "intl": "1.2.5",
    "ionicons": "2.0.1",
    "leaflet": "1.2.0",
    "nebular-icons": "1.1.0",
    "ng2-ckeditor": "^1.2.2",
    "ng2-completer": "2.0.8",
    "ng2-smart-table": "1.3.5",
    "ngx-echarts": "^4.0.1",
    "node-sass": "^4.12.0",
    "normalize.css": "6.0.0",
    "pace-js": "1.0.2",
    "roboto-fontface": "0.8.0",
    "rxjs": "6.5.2",
    "rxjs-compat": "6.3.0",
    "socicon": "3.0.5",
    "tinymce": "4.5.7",
    "tslib": "^1.9.0",
    "typeface-exo": "0.0.22",
    "web-animations-js": "github:angular/web-animations-js#release_pr208",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.2",
    "@angular/cli": "^8.0.2",
    "@angular/compiler-cli": "^8.0.0",
    "@angular/language-service": "8.0.0",
    "@compodoc/compodoc": "1.0.1",
    "@fortawesome/fontawesome-free": "^5.2.0",
    "@types/d3-color": "1.0.5",
    "@types/googlemaps": "^3.30.4",
    "@types/jasmine": "2.5.54",
    "@types/jasminewd2": "2.0.3",
    "@types/leaflet": "1.2.3",
    "@types/node": "6.0.90",
    "codelyzer": "^5.0.1",
    "conventional-changelog-cli": "1.3.4",
    "husky": "0.13.3",
    "jasmine-core": "2.6.4",
    "jasmine-spec-reporter": "4.1.1",
    "karma": "1.7.1",
    "karma-chrome-launcher": "2.1.1",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "1.3.0",
    "karma-jasmine": "1.1.0",
    "karma-jasmine-html-reporter": "0.2.2",
    "npm-run-all": "4.0.2",
    "protractor": "5.1.2",
    "rimraf": "2.6.1",
    "stylelint": "7.13.0",
    "ts-node": "3.2.2",
    "tslint": "^5.7.0",
    "tslint-language-service": "^0.9.9",
    "typescript": "3.4.5"
  }
}

Please help and sorry if I did any stupid mistake, Thank you!

intankirana19 commented 4 years ago

I just found out why it happened because I need to put the token on cookies too, how do I do this? On postman the token I put on header authorization automatically set on cookies thats why the API works

danglephd commented 3 years ago

In my case, I used: token: { class: NbAuthSimpleToken, key: 'access_token', }, The token should put on header authorization because you added it into Interceptor setHeaders: { Authorization: JWT, }, Could you re-check your request header again.