npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ngx-auth/core

v9.0.0

Published

JWT authentication utility for Angular & Angular Universal

Downloads

120

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