@ngx-auth/core

JWT authentication utility for Angular & Angular Universal

Usage no npm install needed!

<script type="module">
  import ngxAuthCore from 'https://cdn.skypack.dev/@ngx-auth/core';
</script>

README

@ngx-auth/core npm version npm downloads

JWT authentication utility for Angular & Angular Universal

CircleCI coverage tested with jest Conventional Commits Angular Style Guide

Please support this project by simply putting a Github star. Share this library with friends on Twitter and everywhere else you can.

@ngx-auth/core is a basic JWT-based authentication utility used for logging in and out of the Angular application and restrict unauthenticated access from accessing restricted routes.

Table of contents:

Getting started

Installation

You can install @ngx-auth/core using npm

npm install @ngx-auth/core --save

Examples

Recommended packages

The following package(s) have no dependency for @ngx-auth/core, however may provide supplementary/shorthand functionality:

  • @ngx-config/core: provides auth settings from the application settings loaded during application initialization

Adding @ngx-auth/core to your project (SystemJS)

Add map for @ngx-auth/core in your systemjs.config

'@ngx-auth/core': 'node_modules/@ngx-auth/core/bundles/core.umd.min.js'

Route configuration

Import AuthGuard using the mapping '@ngx-auth/core' and append canActivate: [AuthGuard] or canActivateChild: [AuthGuard] properties to the route definitions at app.routes (considering the app.routes is the route definitions in Angular application).

app.routes.ts

...
import { AuthGuard } from '@ngx-auth/core';
...
export const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'home',
        component: HomeComponent
      },
      {
        path: 'account',
        children: [
          {
            path: 'profile',
            component: ProfileComponent
          },
          {
            path: 'change-password',
            component: ChangePasswordComponent
          }
        ],
        canActivateChild: [AuthGuard]
      },
      {
        path: 'purchases',
        component: PurchasesComponent,
        canActivate: [AuthGuard]
      },
      {
        path: 'login',
        component: LoginComponent
      }
    ]
  },
  ...
];

app.module configuration

Import AuthModule using the mapping '@ngx-auth/core' and append AuthModule.forRoot({...}) within the imports property of app.module (considering the app.module is the core module in Angular application).

Settings

You can call the forRoot static method using AuthStaticLoader. By default, it is configured to have no settings.

You can customize this behavior (and ofc other settings) by supplying auth settings to AuthStaticLoader.

The following examples show the use of an exported function (instead of an inline function) for AoT compilation.

Setting up AuthModule to use AuthStaticLoader

...
import { AuthModule, AuthLoader, AuthStaticLoader } from '@ngx-auth/core';
...

export function authFactory(): AuthLoader {
  return new AuthStaticLoader({
    backend: {
      endpoint: '/api/authenticate',
      params: []
    },
    storage: localStorage,
    storageKey: 'currentUser',
    loginRoute: ['login'],
    defaultUrl: ''
  });
}

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  ...
  imports: [
    AuthModule.forRoot({
      provide: AuthLoader,
      useFactory: (authFactory)
    }),
    ...
  ],
  ...
  bootstrap: [AppComponent]
})

AuthStaticLoader has one parameter:

  • providedSettings: AuthSettings : auth settings
    • backend: Backend : auth backend (by default, using the endpoint '/api/authenticate')
    • storage: any : storage (by default, localStorage)
    • storageKey: string : storage key (by default, 'currentUser')
    • loginRoute: Array<any> : login route, used to redirect guarded routes (by default, ['login'])
    • defaultUrl: string : default URL, used as a fallback route after successful authentication (by default, '')

:+1: On it! @ngx-auth/core is now ready to perform JWT-based authentication regarding the configuration above.

Note: If your Angular application is performing server-side rendering (Angular Universal), then you should follow the steps explained below.

SPA/Browser platform implementation

  • Remove the implementation from app.module (considering the app.module is the core module in Angular application).
  • Import AuthModule using the mapping '@ngx-auth/core' and append AuthModule.forRoot({...}) within the imports property of app.browser.module (considering the app.browser.module is the browser module in Angular Universal application).

app.browser.module.ts

...
import { AuthModule, AuthLoader, AuthStaticLoader } from '@ngx-auth/core';
...

export function authFactory(): AuthLoader {
  return new AuthStaticLoader({
    backend: {
      endpoint: '/api/authenticate',
      params: []
    },
    storage: localStorage,
    storageKey: 'currentUser',
    loginRoute: ['login'],
    defaultUrl: ''
  });
}

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  ...
  imports: [
    AuthModule.forRoot({
      provide: AuthLoader,
      useFactory: (authFactory)
    }),
    ...
  ],
  ...
  bootstrap: [AppComponent]
})

Server platform implementation.

  • Import AuthModule using the mapping '@ngx-auth/core' and append AuthModule.forServer() within the imports property of app.server.module (considering the app.server.module is the server module in Angular Universal application).

app.server.module.ts

...
import { AuthModule } from '@ngx-auth/core';
...

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  ...
  imports: [
    AuthModule.forServer(),
    ...
  ],
  ...
  bootstrap: [AppComponent]
})

Usage

AuthService has the authenticate and invalidate methods:

The authenticate method posts the credentials to the API (configured at the AuthLoader) using the parameters username and password, and checks the response for a JWT token. If successful, then the authentication response is added to the storage (configured at the AuthLoader) and the token property of AuthService is set.

That token might be used by other services in the application to set the authorization header of http requests made to secure endpoints.

As the name says, the invalidate method clears the JWT token, flushes the authentication response from the storage, and redirects to the login page.

The following example shows how to log in and out of the Angular application.

login.component.ts

...
import { AuthService } from '@ngx-auth/core';

@Component({
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent {
  ...

  username: string;
  password: string;

  constructor(private readonly auth: AuthService) {
    ...
  }

  login(): void {
      this.auth.authenticate(this.username, this.password)
        .subscribe(() => {
          if (!this.auth.isAuthenticated)
            // display warning
        });
  }

  logout(): void {
    this.auth.invalidate();
  }
}

License

The MIT License (MIT)

Copyright (c) 2019 Burak Tasci