@cimpress/simple-auth-wrapper
TypeScript icon, indicating that this package has built-in type declarations

8.6.1 • Public • Published

MEX Simple Auth Wrapper v. 3.0

About

This is a lightweight wrapper for Auth0, removing the need to write and re-write many standard utility functions.

Check out the Changelog to see the latest changes.

Using

To see an example of implementing this wrapper using centralized login with a Cimpress client see Single Page Application Sample

For migrating from embedded auth to centralized auth see Embedded to Centralized Migration

Client Configuration

Using Cimpress Client Configuration, create a Single Page App client configuration. This clientId will be used to configure the wrapper. Add Allowed Callback URLs, Allowed Logout URLs, and Allowed Web Origins corresponding to your application. If you wish to use refresh token, enable Enable Refresh Token Rotation and set refresh token lifetime and refresh token reuse interval.

Import the library and instantiate a new auth helper, passing in the domain, audience, your client ID, useRefreshTokens (optional) and a redirectUri for Auth0 to redirect to (in Auth0 v7 it's called callback url) after authentication. You need to pass in the relative route. For example, "/login". If domain and audience are left blank, domain will default to cimpress.auth0.com0 and audience will default to https://api.cimpress.io/. You probably will not need to manually set these.

npm install @cimpress/simple-auth-wrapper
import { centralizedAuth } from '@cimpress/simple-auth-wrapper';

const auth = new centralizedAuth(options); // see full list of supported options in centralizedauth.js

Then, the following are available to you:

ensureAuthentication(options) combines handleAuthentication and login together. This single call can be used on page load and it will do everything necessary to ensure the user is authenticated. This method accepts the same options object as the login(options) method below.

handleAuthentication() parses the hash that is on the url on return from authentication. This function will automatically redirect you to the url passed into login. Returns a promise that resolves to a boolean of the authentication status.

login(options) Logs a user in with Auth0: first check if an SSO session exists and if so log in with it, if not, redirect to the centralized login page. Returns a promise that resolves to a boolean of the authentication status. Listed below are the available options you can use with this method.

Name Type Default Description
nextUri String "/" If the user cannot be granted a new token via Single Sign On, then they will be taken through the whole webAuth.authorize() flow and will be taken back to this nextUri route.
forceLogin Boolean false If true, the user's auth information will be removed from localStorage forcing them to go through the whole webAuth.authorize() flow (as opposed to getting a new token via Single Sign On).

logout(nextUrl, logoutOfFederated) Logs a user out and removes their token and profile from local storage. Will open URL provided in nextURL. If the optional logoutOfFederated is provided and is true, will also log user out from the identity provider. Note: this is not a common use case and most apps will not need to provide this parameter. For more information reference https://auth0.com/docs/logout

Subscribing to Events

Listed below are the different events you can subscribe to.

Name Description
tokenExpired This event is triggered when the user's token expires. If the user's token in localStorage is expired at the time this event is subscribed to (i.e. auth.on('tokenExpired', ...)) this event will immediately emit. You can turn this behavior off via the emitInitialTokenExpired constructor option. By default this event will emit 30 seconds before the actual expiry. You can change this offset value via the expirationOffset constructor option. It is also possible for this to be fired on browser focus. This is controlled by the checkExpirationOnFocus constructor option and exists because the token expired timer can be unreliable when the user's computer is asleep.
import { centralizedAuth } from '@cimpress/simple-auth-wrapper';

const auth = new centralizedAuth(options);

auth.on('tokenExpired', () => {
  // This is invoked each time the current token in localStorage becomes expired.
  // This will also be immediately invoked if the token in localStorage is already expired. (configurable via emitInitialTokenExpired)
  console.log('The token in local storage is expired.');
});

Delegation

Delegation is no longer part of the core wrapper. If you have a need for it, you can load it and optionally patch it to the auth object:

import { centralizedAuth, Delegation } from '@cimpress/simple-auth-wrapper';

const auth = new centralizedAuth(options);

const delegationHandler = new Delegation(auth);

auth.buildDelegationHeader = delegationHandler.buildDelegationHeader;

This will give you access to:

buildDelegationHeader(targetClientId) Build some fetch headers, getting the delegation token if needed. Note: delegation is deprecated and not recommended. We recommend using access token instead.

getDelegationToken(targetClientId) get a delegation token for the given target clientid. Note: delegation is deprecated and not recommended. We recommend using access token instead.

User metadata

User metadata is a place to store application settings for the users

import { UserMetadata } from '@cimpress/simple-auth-wrapper';
const auth; // your instantiated auth Wrapper

const userMetadata = new UserMetadata(auth);

userMetadata will then give you access to:

getUserMetadata(applicationKey) applicationKey is optional (defaults to app clientId). Gets a JSON object of all the applications UserMetadata

patchUserMetadata(userMetadata, applicationKey) applicationKey should match what is used for get. Puts the metadata into the users UserMetadata

Authorization Code Grant Flow

The Authorization Code Grant Flow can be used to retrieve a refresh token for a user.

import { AuthorizationCodeGrant } from '@cimpress/simple-auth-wrapper';
const authorizationCodeGrant = new AuthorizationCodeGrant(options);
Name Type Default Description
clientID String None (required) The clientID used in the Authorization Code Grant Flow
redirectRoute String "" The route Auth0 will redirect back to: window.location.origin + redirectRoute
domain String cimpress.auth0.com The auth0 domain
audience String https://api.cimpress.io/ The auth0 audience
scope String offline_access The scope which you want to request access for

This will give you access to:

login(options) Starts the Authorization Code Grant Flow, redirecting the user to the centralized lock page.

Name Type Default Description
nextUri String / Takes the user through the flow and will be returned to this nextUri route.
authParams Object {} Optionally, pass additional parameters to the /authorize url created by auth0.js. Useful for cases where you must send additional data to an IDP.

handleAuthentication(options) Resumes the authorization code grant flow. Should be called at the base of your application, or at the redirectUri specified to continue the flow. Returns a Promise of { authorizationCode, redirectUri, nextUri }

Name Type Default Description
performRedirect Boolean true Indicates if the wrapper should redirect back to the specified nextUri

Authorization Code Flow with Proof Key for Code Exchange (PKCE)

The Authorization Code Flow With PKCE can be used to retrieve a refresh token for a user. This is used along with the Sessions API where the session is used to retireve an access token for the user.

Why the change from AuthorizationCodeGrant to AuthorizationCodeGrantPKCE?

When public clients (e.g., native and single-page applications) request Access Tokens, some additional security concerns (Cannot securely store a Client Secret) are posed that are not mitigated by the Authorization Code Flow alone.

To mitigate this, The PKCE-enhanced Authorization Code Flow introduces a secret created by the calling application that can be verified by the authorization server; this secret is called the Code Verifier. Additionally, the calling app creates a transform value of the Code Verifier called the Code Challenge and sends this value over HTTPS to retrieve an Authorization Code. This way, a malicious attacker can only intercept the Authorization Code, and they cannot exchange it for a token without the Code Verifier.

import  {  AuthorizationCodeGrantPKCE  }  from  '@cimpress/simple-auth-wrapper';

const  authorizationCodeGrantPKCE  =  new  AuthorizationCodeGrantPKCE(options);
Name Type Default Description
clientID String None (required) The clientID used in the Authorization Code Grant Flow
redirectRoute String "" The route Auth0 will redirect back to: window.location.origin + redirectRoute
domain String cimpress.auth0.com The auth0 domain
audience String https://api.cimpress.io/ The auth0 audience
scope String offline_access The scope which you want to request access for

This will give you access to:

login(options) Starts the Authorization Code Grant Flow, redirecting the user to the centralized lock page.

Name Type Default Description
nextUri String / Takes the user through the flow and will be returned to this nextUri route.

handleAuthentication(options) Resumes the authorization code grant flow. Should be called at the base of your application, or at the redirectUri specified to continue the flow. Returns a boolean value indicating whether the User has successfully completed the authorization code grant flow.

Name Type Default Description
performRedirect Boolean true Indicates if the wrapper should redirect back to the specified nextUri

ensureAuthentication(options) combines handleAuthentication and login together. This single call can be used on page load and it will do everything necessary to ensure the user is authenticated.

Name Type Default Description
nextUri String / Takes the user through the flow and will be returned to this nextUri route.
forceLogin String / Forcefully redirect the user to the centralized lock page.

getProfile(sessionId) returns the profile information of a user in exchange of a sessionId. This makes a call to the Profile Service API to fetch the information and to avoid multiple calls to API, we cache the profile information for a set interval (1 hour) before invoking the profile service again.

logout(nextUri) closes the active session and clears the local storage. After logging the user out, the user is sent to the url specified in 'nextUri'. If nextUri is a relative path then the user will be sent to window.location.origin + nextUri

isLoggedIn(sessionId) returns whether the current session is Active.

Subscribing to Events

Listed below are the different events you can subscribe to.

Name Description
sessionExpired This event is triggered when the user's session expires. By default this event will emit 30 seconds before the actual expiry. You can change this offset value via the sessionExpirationOffset constructor option. It is also possible for this to be fired on browser focus. This is controlled by the checkExpirationOnFocus constructor option and exists because the session expired timer can be unreliable when the user's computer is asleep.
import { AuthorizationCodeGrantPKCE } from '@cimpress/simple-auth-wrapper';

const auth = new AuthorizationCodeGrantPKCE(options);

auth.on('sessionExpired', () => {
  console.log('The session has expired.');
});

Step-up authentication

initiateStepupLogin(nextUri, logoutOfFederated, ttl) This function is responsible for initiating the step-up login process. It takes the following parameters:

Name Type Default Description
nextUri String / Takes the user through the flow and will be returned to this nextUri route.
logoutOfFederated Boolean false If the optional logoutOfFederated is provided and is true, will also log user out from the identity provider. Note: this is not a common use case and most apps will not need to provide this parameter. For more information reference https://auth0.com/docs/logout
ttl Number undefined Time to live, representing the expiration time of the step up token.

getStepUpExpiryTime() provides the time at which an step up token, resulting from the step up authentication, is set to expire.

Readme

Keywords

none

Package Sidebar

Install

npm i @cimpress/simple-auth-wrapper

Weekly Downloads

2,726

Version

8.6.1

License

Apache-2.0

Unpacked Size

204 kB

Total Files

29

Last publish

Collaborators

  • ryanbreen
  • bmcglynn
  • ctmex
  • fswiecki
  • dboerlage