@cimpress/simple-auth-wrapper

中文文档
11.0.1发布于 2026/08/07Apache-2.0TypeScriptESM + CJS近 30 天下载 1.8万

A simple utility class to wrap basic Auth0 functionality

原始使用文档
文档目录7 节
  1. About
  2. Using
  3. Client Configuration
  4. Delegation
  5. Authorization Code Grant Flow
  6. Authorization Code Flow with Proof Key for Code Exchange (P…
  7. Step-up authentication

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.

NameTypeDefaultDescription
nextUriString"/"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.
forceLoginBooleanfalseIf 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.

NameDescription
tokenExpired(Note: version specific) 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. If you are using version 9 and below then you can turn this behavior off via the emitInitialTokenExpired constructor option for version 10 and above this feature is now by default off. 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.

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);
NameTypeDefaultDescription
clientIDStringNone (required)The clientID used in the Authorization Code Grant Flow
redirectRouteString""The route Auth0 will redirect back to: window.location.origin + redirectRoute
domainStringcimpress.auth0.comThe auth0 domain
audienceStringhttps://api.cimpress.io/The auth0 audience
scopeStringoffline_accessThe 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.

NameTypeDefaultDescription
nextUriString/Takes the user through the flow and will be returned to this nextUri route.
authParamsObject{}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 }

NameTypeDefaultDescription
performRedirectBooleantrueIndicates 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);

NameTypeDefaultDescription
clientIDStringNone (required)The clientID used in the Authorization Code Grant Flow
redirectRouteString""The route Auth0 will redirect back to: window.location.origin + redirectRoute
domainStringcimpress.auth0.comThe auth0 domain
audienceStringhttps://api.cimpress.io/The auth0 audience
scopeStringoffline_accessThe 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.

NameTypeDefaultDescription
nextUriString/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.

NameTypeDefaultDescription
performRedirectBooleantrueIndicates 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.

NameTypeDefaultDescription
nextUriString/Takes the user through the flow and will be returned to this nextUri route.
forceLoginString/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.

NameDescription
sessionExpiredThis 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:

NameTypeDefaultDescription
nextUriString/Takes the user through the flow and will be returned to this nextUri route.
logoutOfFederatedBooleanfalseIf 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
ttlNumberundefinedTime 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.

版本与发布记录

@cimpress/simple-auth-wrapper 共发布 82 个版本,首次发布于 2017/12/06;过去 12 个月发布了 4 个版本。

版本发布日期距今
11.0.1latest2026/08/073 个月前
11.0.02026/07/014 个月前
10.0.22026/04/106 个月前
10.0.12026/01/309 个月前
10.0.02025/09/031.2 年前
9.0.12025/08/131.2 年前

关于 @cimpress/simple-auth-wrapper 的常见问题

@cimpress/simple-auth-wrapper 是什么?

A simple utility class to wrap basic Auth0 functionality

如何安装 @cimpress/simple-auth-wrapper?

在项目目录运行 npm install @cimpress/simple-auth-wrapper,或使用 pnpm add / yarn add / bun add。

@cimpress/simple-auth-wrapper 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cimpress/simple-auth-wrapper 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@cimpress/simple-auth-wrapper 可以商用吗?

@cimpress/simple-auth-wrapper 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@cimpress/simple-auth-wrapper 的下载量有多少?

根据 npm 官方下载统计,@cimpress/simple-auth-wrapper 在 2026/10/10 – 2026/11/08 这 30 天内被下载 18,165 次,日均约 606 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cimpress/simple-auth-wrapper 还在维护吗?

最新版本 11.0.1 发布于 2026/08/07(3 个月前);至今共发布 82 个版本,其中过去 12 个月发布了 4 个;首次发布于 2017/12/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。