@ngx-auth/auth0

Auth0 platform implementation of ngx-auth

Stats

stars 🌟issues ⚠️updated 🛠created 🐣size 🏋️‍♀️
561Apr 27, 2020Aug 26, 2017Minified + gzip package size for @ngx-auth/auth0 in KB

Readme

@ngx-auth/auth0 npm version npm downloads

Auth0 platform implementation of ngx-auth

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.

Table of contents:

Getting started

Installation

You can install @ngx-auth/auth0 using npm

npm install @ngx-auth/auth0 --save

Examples

Related packages

The following packages may be used in conjunction with @ngx-auth/auth0:

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

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

'@ngx-auth/auth0': 'node_modules/@ngx-auth/auth0/bundles/auth0.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).

NOTICE

You should define a callback url (here we use auth-callback) handling the Auth0 callback process, and a public url as a landing component (to prevent infinite loop on routing where no public interfaces exist).

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: 'public',
        component: PublicComponent
      },
      {
        path: 'auth-callback',
        component: AuthCallbackComponent
      }
    ]
  },
  ...
];

app.module configuration

Import Auth0Module using the mapping '@ngx-auth/auth0' and append Auth0Module.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 Auth0StaticLoader. By default, it is configured to have no settings.

You can customize this behavior (and ofc other settings) by supplying auth0 settings to Auth0StaticLoader.

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

Setting up Auth0Module to use Auth0StaticLoader

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

export function auth0Factory(): AuthLoader {
  return new Auth0StaticLoader({
    backend: {
      clientID: 'YOUR_AUTH0_CLIENT_ID',
      domain: 'YOUR_APP_NAME.us.auth0.com',
      redirectUri: 'http://YOUR_APP_URL/auth-callback',
      scope: 'openid',
      responseType: 'token id_token'
    },
    storage: localStorage,
    storageKey: 'currentUser',
    publicRoute: ['public'],
    defaultUrl: ''
  });
}

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

Auth0StaticLoader has one parameter:

  • providedSettings: AuthSettings : auth settings
    • backend: Backend : auth0 backend
    • storage: any : storage (by default, localStorage)
    • storageKey: string : storage key (by default, 'currentUser')
    • loginRoute: Array<any> : public route, used as a landing component (by default, ['public'])
    • defaultUrl: string : default URL, used as a fallback route after successful authentication (by default, '')

:+1: Hellcat! @ngx-auth/auth0 is now ready to do some magic with Auth0 using 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 Auth0Module using the mapping '@ngx-auth/auth0' and append Auth0Module.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 { AuthLoader, AuthModule } from '@ngx-auth/core';
import { Auth0Module, Auth0StaticLoader } from '@ngx-auth/auth0';
...

export function auth0Factory(): AuthLoader {
  return new Auth0StaticLoader({
    backend: {
      clientID: 'YOUR_AUTH0_CLIENT_ID',
      domain: 'YOUR_APP_NAME.us.auth0.com',
      redirectUri: 'http://YOUR_APP_URL/auth-callback',
      scope: 'openid',
      responseType: 'token id_token'
    },
    storage: localStorage,
    storageKey: 'currentUser',
    publicRoute: ['public'],
    defaultUrl: ''
  });
}

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

Server platform implementation.

  • Import Auth0Module using the mapping '@ngx-auth/auth0' and append Auth0Module.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';
import { Auth0Module } from '@ngx-auth/auth0';
...

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

Usage

Auth0Service has the authorize, authenticate and invalidate methods:

The authenticate method invokes the WebAuth.parseHash method to build the access_token, id_token and expiresAt. If successful, then the tokens are added to the storage (configured at the AuthLoader) and the accessToken, idToken and expiresAt properties of Auth0Service are set.

These tokens 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 tokens, flushes the authentication response from the storage, and redirects to the login page.

License

The MIT License (MIT)

Copyright (c) 2019 Burak Tasci

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.