Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

aurelia-authentication

spoonx1.3kMIT3.8.3TypeScript support: included

Plugin for social media authentication and local authentication together with other authentication utilities.

aurelia, oauth, authentication

readme

aurelia-authentication

Build Status Known Vulnerabilities Gitter

Aurelia-authentication is a token-based authentication plugin for Aurelia with support for popular social authentication providers (Google, Twitter, Facebook, LinkedIn, Windows Live, FourSquare, Yahoo, Github, Instagram) and a local strategy, i.e. simple username / email and password. It developed of a fork of paul van bladel's aurelia-auth which itself is a port of the great Satellizer library.

Aurelia-authentication makes local and third-party authentication easy. Aurelia-authentication does not use any cookies but relies on a token (designed for JWT, but has basic support for others as well) stored in the local storage of the browser. If your server is setup right, it can be a simple as just to select your server endpoint from your aurelia-api setup, add your third-party client ids and you are ready to go.

You have multiple endpoints? No problem! In the recommended setting, aurelia-authentication makes use of aurelia-api which can set up multiple endpoints. Just specify in your aurelia-authentication configuration which endpoint you want to use for your server and which further endpoints you want to be configured and your token will be sent automatically to your protected API when the user is authenticated.

With aurelia-authentication you can:

  • Use local login or third-party providers to authenticate the user
  • Automatically add your token to requests to the specified endpoints
  • Automatically refresh your token
  • Extensively customize the settings
  • Use standalone or in conjunction with aurelia-api
  • Use Auth0 as your only authentication provider (see the relevant section for more info)
  • Update valueConverters using the 'authorization-change' binding signal.
  • Subscribe to the 'authorization-change' event.
  • And more

Documentation

You can find usage examples and the documentation at the aurelia-authentication-docs.

The changelog provides you with information about important changes.

Installation

Aurelia-Cli

Run npm i aurelia-authentication --save from your project root.

Aurelia-authentication needs an installation of aurelia-api. It also has submodules (currently only the authFilter) and makes use of extend and jwt-decode. So, add following to the build.bundles.dependencies section of aurelia-project/aurelia.json.

"dependencies": [
  // ...
  "extend",
  {
    "name": "aurelia-authentication",
    "path": "../node_modules/aurelia-authentication/dist/amd",
    "main": "aurelia-authentication"
  },
  {
    "name": "jwt-decode",
    "path": "../node_modules/jwt-decode/lib",
    "main": "index"
  }
  // ...
],

Jspm

Run jspm i aurelia-authentication

Add aurelia-authentication to the bundles.dist.aurelia.includes section of build/bundles.js.

Aurelia-authentication needs an installation of aurelia-api. It also has submodules. They are imported in it's main file, so no further action is required.

If the installation results in having forks, try resolving them by running:

jspm inspect --forks
jspm resolve --only registry:package-name@version

E.g.

jspm inspect --forks
>     Installed Forks
>         npm:aurelia-dependency-injection 1.0.0-beta.1.2.3 1.0.0-beta.2.1.0

jspm resolve --only npm:aurelia-dependency-injection@1.0.0-beta.2.1.0

Webpack

Run npm i aurelia-authentication --save from your project root.

The authFilter needs to be added to the webpack.config.js.

Run npm i ModuleDependenciesPlugin --save-dev from your root project and include it the webpack.config.js, eg:

const { AureliaPlugin, ModuleDependenciesPlugin  } = require('aurelia-webpack-plugin');`

In the plugins section add the authFilter, eg:

  plugins: [
    new AureliaPlugin(),
    new ModuleDependenciesPlugin({
      "aurelia-authentication": [ "./authFilterValueConverter" ],
    }),

Aurelia-authentication needs an aurelia-api. It also has submodules. They are listed as resources in the package.json. So, no further action is required.

Typescript

Npm-based installations pick up the typings automatically. For Jspm-based installations, add to your typings.json:

"aurelia-authentication": "github:spoonx/aurelia-authentication",

and run typings i

or run

typings i github:spoonx/aurelia-authentication

Usage

Add a configuration file

Set your custom configuration. You can find all options and the default values in the baseConfig.

/* authConfig.js */
var baseConfig = {
    endpoint: 'auth',             // use 'auth' endpoint for the auth server
    configureEndpoints: ['auth'], // add Authorization header to 'auth' endpoint
    facebook: {
        clientId: 'your client id' // set your third-party providers client ids
    }
}

Configure the plugin

Register the plugin and apply your authConfig.

/* main.js */
import authConfig from './authConfig';

aurelia.use
  /* Your other plugins and init code */
  .plugin('aurelia-api', config => {
    // Register an authentication hosts
    config.registerEndpoint('auth');
  })
  /* configure aurelia-authentication */
  .plugin('aurelia-authentication', baseConfig => {
      baseConfig.configure(authConfig);
  });

Use AuthService in a view-model

import {AuthService} from 'aurelia-authentication';
import {inject} from 'aurelia-framework';

@inject(AuthService)
export class Login {
    constructor(authService) {
        this.authService   = authService;
        this.authenticated = false;
    };

    // use authService.login(credentialsObject) to login to your auth server
    // authService.authenticated holds the current status
    // authService.getPayload() gives you the current payload object (for jwt)
    login(credentialsObject) {
      return this.authService.login(credentialsObject)
        .then(() => {
            this.authenticated = this.authService.authenticated;
        });
    };

    // use authService.logout to delete stored data
    // set expiredRedirect in your settings to automatically redirect
    logout() {
      return this.authService.logout()
        .then(() => {
          this.authenticated = this.authService.authenticated;
        });
    }

    // use authService.authenticate(name) to get third-party authentication
    authenticateFacebook() {
      return this.authService.authenticate('facebook')
        .then(() => {
          this.authenticated  = this.authService.authenticated;
        });
    }
}

Quick authService api overview

authService
  // the Rest instance of aurelia-api used for requests. '.client.client' is the used httpClient instance (from aurelia-fetch-client)
  .client
  // the current authentication status
  .authenticated
  // signup into server with credentials and optionally logs in
  signup(displayNameOrCredentials, emailOrOptions, passwordOrRedirectUri, options, redirectUri)
  // log into server with credentials. Stores response if successful
  login(emailOrCredentials, passwordOrOptions, optionsOrRedirectUri, redirectUri)
  // deletes stored response. If configured in the config, sends optionally a logout request. 
  logout(redirectUri, query, name)
  // manually refresh authentication. Needs refreshToken options to be configured
  .updateToken()
  // link third-party account or log into server via third-party authentication. Stores response if successful
  authenticate(name, redirectUri, userData)
  // unlink third-party
  unlink(name, redirectUri)
  // get profile
  .getMe(criteriaOrId)
  // update profile
  .updateMe(body, criteriaOrId)
  // check if token is available and, if applicable, not expired
  .isAuthenticated()
  // get token payload if available
  .getTokenPayload()
  // get the token ttl if available
  .getTtl()
  // get the token exp if available
  .getExp()

Additionally, you can use AuthFilterValueConverter and AuthenticatedStep for UI feedback.

You can find more information in the aurelia-authentication-docs.

Note

Some month ago, we've simplified installation and usage! This plugin should now be installed using jspm i aurelia-authentication or (for webpack) npm i aurelia-authentication --save. Make sure you update all references to spoonx/aurelia-authentication and spoonx/aurelia-api and remove the spoonx/ prefix (don't forget your config.js, package.json, imports and bundles).

changelog

3.8.3 (2019-05-01)

Bug Fixes

  • authService: add tests (dcf3b09)
  • authService: move IE relevant code higher (3f428e1)
  • authService: update internal authentication fields (86620c0)

3.8.2 (2018-09-24)

Bug Fixes

  • auth0: extend responseType check (2d3434b), closes #403
  • auth0: fix access and id token assignments (9e2c383), closes #397

3.8.1 (2018-06-13)

Bug Fixes

  • fetchClientConfig: do not break promises chain (c1cd0f2)

3.8.0 (2018-05-28)

Bug Fixes

  • authService: detect logout events in different tabs when using autoupdate of tokens. (75029b2), closes #379
  • authService: limit setTimeout to it's maximum value of about ca 24.85d (3c51df6), closes #375
  • authService: use proper update method (0283882)
  • baseConfig: logoutOnInvalidtoken -> logoutOnInvalidToken (16bb54b)
  • index: use PLATFORM.moduleName for globalResources (ec84731)

Features

  • authentication: add option to always store all received properties (be7c530)
  • authService: added getIdTokenPayload method (0651f00)
  • baseConfig: added azure ad configuration (554da43)

3.7.0 (2017-06-29)

Bug Fixes

  • authentication: prevent logout if there is no identity (aea4ac8)
  • authService: redirect on refresh token failure when configured to do so (f23fd60)

BREAKING CHANGES

  • authentication: authentication failures on 401 now return the response in the rejection.

3.6.0 (2017-05-05)

Features

  • fetchClientConfig: logout when token is invalidated by server (ad9b66a)

3.5.0 (2017-04-25)

Features

  • authService: add default headers and clientSecret in config (863e4a4)

3.4.1 (2017-03-23)

Bug Fixes

  • authService: storageEventHandler change (01d3662)

3.4.0 (2017-03-20)

Features

  • authService: support empty login request (0d8f258)

3.3.0 (2017-03-06)

Bug Fixes

  • authService: handle logout also if server logoutUrl fails (403a498)

Features

  • authentication: include response object in 'Token not found in response' errors (d5131ca)

3.2.0 (2017-01-13)

Bug Fixes

  • authService: allow object passed as second arg to authService.login() (da294c4)
  • interceptor: fix automatic refresh token usage (62d61de)

3.1.0 (2016-11-02)

Bug Fixes

  • auth0: Close popup after an unrecoverable error (36aa441)
  • auth0: Fix auth rejection for non severe errors (9a91ef2)

Features

  • authService: Add focus handler to check token expiration (38381c3)
  • authService: changed redirection overwrite to empty string (cc8b79e)
  • authService: optional callback for isAuthenticated (fdbe4b5)

3.0.3 (2016-10-14)

Bug Fixes

  • baseConfig: explain getExpirationDateFromResponse and ensure format (ee30ce4)
  • isAuthenticated: always check access_token existence (72fb377)

3.0.2 (2016-10-14)

Bug Fixes

  • authService: storageChangedReload optional (default: false) (8c5b1cb)

3.0.1 (2016-10-13)

Bug Fixes

  • authServive: fix ie11 storage event loop (b9ce956)

Features

  • authService: ensure page reload after storage events (7125cc5)

3.0.0 (2016-10-05)

Bug Fixes

  • authService: storage events do not work properly in IE11 (944a716)

Features

  • auth0lock: Upgrade code to work with Auth0 Lock 10.x (no backwards compat) (fe3adc7)
  • authService: add logout handling for openid connect (91e9217)

3.0.0-rc11 (2016-09-22)

Bug Fixes

  • authService: storage events do not work properly in IE11 (944a716)

Features

  • authService: add logout handling for openid connect (91e9217)

3.0.0-rc10 (2016-08-25)

Bug Fixes

  • bundle: re-add imports for bundling (4b6208c)

3.0.0-rc9 (2016-08-23)

Bug Fixes

  • authService: let authService.isAuthenticated analyse token from storage each time (as was intended) (e2ef686)
  • authService: listen to storage events. fixes login/logout in other tabs (52c2f67)
  • oauth implicit: removed encoding of space character between response types when returning token from popup. (e444e0b)

Features

  • authService: add getIdToken method to authenticaton and authService (00a7368)
  • config: optional functions getExpirationDateFromResponse, getAccessTokenFromResponse and getRefreshTokenFromResponse (352e5a4)

BREAKING CHANGES

  • authService: hasDataAnalyzed renamed to responseAnalyzed

3.0.0-rc8 (2016-08-03)

Bug Fixes

  • popup: removed '#' character from hash fragment in redirect URL from popup. (Issue #223). (baf9148)

3.0.0-rc7 (2016-07-22)

3.0.0-rc6 (2016-07-04)

<a name"3.0.0-rc5">

3.0.0-rc5 (2016-06-15)

Bug Fixes

(41454e39)

  • baseConfig:
    • remove double entry current (15f221c8)
    • revert to only globalValueConverters=["authFilterValueConverter"] (again) (118cbd2d)

<a name"3.0.0-rc4">

3.0.0-rc4 (2016-06-09)

Bug Fixes

  • ValueConverter: fix ValueConverter build (c0b71009)
  • ValueConverters: bring back old authFilter version since new one can't be auto bundled (a66394dc)
  • authService:
    • actually clear timeout (1a887abf)
    • initialize with stored responseObject (d50f9257)
  • authentication: consistent throw if token not found (41454e39)
  • popup:
    • use PLATFOTM.global.document.location (fa0e8a30)
  • project:
    • use auth:true for authenticationStep and isAuth (caf4a3be)

Features

  • authService:
    • redirection when token expired optional (b6ed192f)
    • add onLogout. something is needed to eg clear cookies after authomatic logout (8ade299d)
    • actually logout on timeout (d65ca7ba)
  • authenticateStep: use authService.authenticate (5b9306fe)
  • project: (234e1024)
  • value-converters: move/rename/add valueConverters (4d2ee936)

<a name"3.0.0-rc3">

3.0.0-rc3 (2016-06-02)

Bug Fixes

  • aurelia-authentication: add ie9 window.origin polyfill (a06e66b0)
  • auth0Lock: add missing aurelia-pal dependency for webpack (a8056dc3)
  • authentication: consistent throw if token not found (41454e39)
  • popup: encodeURIComponent all query parameters (82e023c2)
  • project: restore missing props in package.json for jspm 0.17+ (17f9e81d)

Features

  • BaseConfig: copied over current sahat/satellizer settings (70dfb814)
  • authService:
    • use authenticated and setTimeout for login status (d57e1142)
    • add getExp() (026d0d82)
    • add profileMethod config option (218fffc1)
    • optional logout request (d65ca7ba)
  • authentication:
    • use jwt-decode to decode token (f5056ce9)
    • add support for auth0 login using lock (97e625e8)
    • allow dotted accessTokenProp (27198f8f)
    • add deprecation warning for provider.type (replaced by provider.oauthType) (bcdf06ba)
  • project:
    • use aurelia-pal for window and document (fdbb9189)
    • add AuthenticationStep and deprecate AuthorizeStep (baeb35c4)
  • refresh-token: optional refreshTokenUrl (234e1024)

<a name"3.0.0-rc2">

3.0.0-rc2 (2016-05-04)

Bug Fixes

  • authentication: let the storageKey be the storageKey (a302352b)
  • typings: mark optional parameters (f56df76a)

<a name"3.0.0-rc1">

3.0.0-rc1 (2016-04-28)

Bug Fixes

  • BaseConfig: encode redirect url for all providers (adc90827)
  • authUtils: quote string (ab4756f2)
  • d.ts: include only necessary imports (2c292ac4)

Features

  • AuthService:
    • updateToken handles multiple calls (b6199531)
    • isAuthenticated optionally as promise (9c85af79)
  • authService: add request options to signup and login as well as optional redirecUri overwrite (e8072e54)
  • baseConfig:
    • standardize access token option names (breaking) (29d22c5a)
    • change refreshTokenName option value and add refreshTokenProp (breaking) (c8885d7b)
    • replace both tokenPrefix options with tokenStorage (breaking) (4f98493b)
  • project:
    • revert isAuthenticated to just boolean again. use aurelia-logger and @deprecated (49fe1e0f)
    • store the complete response in storage. AuthService.getTimeLeft() added (b98d839e)
    • bundle into single file (6984c590)
    • Rename project to remove spoonx prefix. enable npm installation (637aac41)
    • name auth appropriatly and refactor (95259767)

Breaking Changes

  • for AuthService(provider, redirectUri, userData) redirectUri===false means "Do not redirect" now. Set redirectUrl to undefined or null to use the defaultRedirectUrl.(which is in this case BaseConfig.loginRedirect) DEPRECATED: for AuthService(provider, redirectUri, userData) redirectUri === true to actually not redirect is deprecated. Set redirectUrl===false instead.

    (2c15244b)

  • authUtils got removed. Extend and aurelia-path are used instead for some functions

    (671f087a)

  • This aligns access token option names with the refresh token option names. The option changes are as follows:
tokenStorage      => accessTokenStorage
responseTokenProp => accessTokenProp
tokenName         => accessTokenName
tokenRoot         => accessTokenRoot

(29d22c5a)

  • refreshTokenName option value has been changed from 'refresh_token' to 'token'. The new refreshTokenProp option is set to 'refresh_token' by default (a non-breaking change).

    (c8885d7b)

  • Token prefixes were using another 'unrelated' option to make up the full storage keys. This was unnecessary, confusing and could have resulted in the same storage location being shared between both the refresh and access tokens. README updated to reflect current design.

    (4f98493b)

  • all imports need to use 'aurelia-authenticaton'

    (6984c590)

  • spoonx/ prefix dropped from install name for authentication and api. Update package.json and config.js accordingly.

    (637aac41)

  • AuthService instance renamed to authService and Authentication instance renamed to authentication

    (95259767)

<a name"2.1.0">

2.1.0 (2016-03-31)

Bug Fixes

  • configure: fail if specified endpoints are not registered (4a444253)
  • interceptor: set authorization header instead of appending (4e53457d)

Features

<a name"2.0.2">

2.0.2 (2016-03-30)

Bug Fixes

  • authFilter: Import authfilter for bundling (d5461fd6)

<a name"2.0.1">

2.0.1 (2016-03-29)

<a name"2.0.0">

2.0.0 (2016-03-29)

<a name"1.1.2">

1.1.2 (2016-03-26)

Bug Fixes

  • project: fix wrong dependency introduced in 1.1.1 (1b288214)

<a name"1.1.1">

1.1.1 (2016-03-25)

<a name"1.1.0">

1.1.0 (2016-03-25)

Features

  • authUtils: make authUtils a named export, export authUtils from index -- breaking change! (7de0aa23)

<a name"1.0.1">

1.0.1 (2016-03-22)

Bug Fixes

  • FetchConfig: keep client settings when adding interceptor (18c052c1)

<a name"1.0.0">

1.0.0 (2016-03-19)

Breaking Changes

  • The project now must be imported with aurelia-authentication

    (ba66705d)

<a name"0.13.9">

0.13.9 (2016-03-17)

Bug Fixes

  • authorizeStep: fix redirect if isLoggedIn and on login route (65986f7c)
  • baseConfig: SPA redirects should be hashed (a24ce935)
  • project: import authFilter for inclusion when bundling (d70a5c6f, closes #44)

<a name"0.13.8">

0.13.8 (2016-03-02)

<a name"0.13.7">

0.13.7 (2016-02-09)

<a name"0.13.6">

0.13.6 (2016-02-08)

Bug Fixes

  • oauth: use current provider settings (9c860c23)

<a name"0.13.4">

0.13.4 (2016-01-28)

Bug Fixes

  • oAuth: reset defaults properly (968abfcf)

<a name"0.13.3">

0.13.3 (2016-01-24)

Features

  • typescript: Add proper build support (9ebfd763)
  • authentication: use current tokenName (bd58f00b)

<a name"0.13.2">

0.13.2 (2016-01-23)

Bug Fixes

  • index: fetchConfig needs configured baseConfig (e62c9eb9)

<a name"0.13.1">

0.13.1 (2016-01-21)

Bug Fixes

  • popup: Referrence popupWindow on this; popupWindow is undefined. (212117e9)

<a name"0.13.0">

0.13.0 (2016-01-19)

Bug Fixes

Features

  • build:
    • Create typescript definitions file on build (09f63b1b)
    • Added typescript ds file generating (e5d4726a)
  • fetch-config: Added endpoint configuring, and configurable client. (c1e30f61)
  • project: Added typescript definition file (28804352)
  • snyk: Added snyk (562ba14e)

0.12.4 (2016-01-14)

Bug Fixes

0.12.3 (2016-01-14)

Features

  • project: Added typescript definition file (28804352)

0.12.2 (2016-01-14)

Bug Fixes

  • authentication: Catch corrupt json (b971cfc1)

Features

  • authService: getMe with optional criteria (99b8ed62)

0.12.1 (2016-01-13)

Features

  • authService: getMe with optional criteria (99b8ed62)

0.12.0 (2016-01-02)

Bug Fixes

  • project: Version bump to higher than all previous ones (c4ceae9b)

0.1.2 (2015-12-29)

Refactor

  • authentication: Made response token configurable (8281d906)

0.1.1 (2015-12-24)

Features

  • fetch-client: Recover baseUrl from singleton (8281d906)
  • lint: Added linting (5cf127b2)