
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
@auth0/auth0-spa-js
Advanced tools
Auth0 SDK for Single Page Applications using Authorization Code Grant Flow with PKCE
@auth0/auth0-spa-js is a JavaScript library designed to handle authentication in single-page applications (SPAs) using Auth0. It provides a simple and secure way to integrate Auth0's authentication and authorization services into your SPA.
Login
This feature allows users to log in to your application using Auth0. The code sample demonstrates how to create an Auth0 client and initiate a login redirect.
const auth0 = await createAuth0Client({
domain: 'YOUR_DOMAIN',
client_id: 'YOUR_CLIENT_ID'
});
await auth0.loginWithRedirect({
redirect_uri: window.location.origin
});
Logout
This feature allows users to log out of your application. The code sample shows how to log out and redirect the user to the home page.
await auth0.logout({
returnTo: window.location.origin
});
Get User Information
This feature retrieves the authenticated user's information. The code sample demonstrates how to get the user profile after authentication.
const user = await auth0.getUser();
console.log(user);
Token Handling
This feature handles token retrieval for authenticated requests. The code sample shows how to get an access token silently without redirecting the user.
const token = await auth0.getTokenSilently();
console.log(token);
oidc-client is a JavaScript library for OpenID Connect (OIDC) and OAuth2. It provides similar functionalities for handling authentication and authorization in SPAs. Compared to @auth0/auth0-spa-js, oidc-client is more generic and can be used with any OIDC-compliant identity provider.
Firebase Authentication provides backend services to help authenticate users in your application. It supports various authentication methods, including email/password, phone, and social providers. Unlike @auth0/auth0-spa-js, Firebase offers a broader range of services beyond authentication, such as database and hosting.
Auth0 SDK for Single Page Applications using Authorization Code Grant Flow with PKCE.
From the CDN:
<script src="https://cdn.auth0.com/js/auth0-spa-js/1.18/auth0-spa-js.production.js"></script>
Using npm:
npm install @auth0/auth0-spa-js
Using yarn:
yarn add @auth0/auth0-spa-js
Create an Auth0Client
instance before rendering or initializing your application. You should only have one instance of the client.
import createAuth0Client from '@auth0/auth0-spa-js';
//with async/await
const auth0 = await createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>'
});
//with promises
createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>'
}).then(auth0 => {
//...
});
//or, you can just instantiate the client on it's own
import { Auth0Client } from '@auth0/auth0-spa-js';
const auth0 = new Auth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>'
});
//if you do this, you'll need to check the session yourself
try {
await getTokenSilently();
} catch (error) {
if (error.error !== 'login_required') {
throw error;
}
}
<button id="login">Click to Login</button>
//with async/await
//redirect to the Universal Login Page
document.getElementById('login').addEventListener('click', async () => {
await auth0.loginWithRedirect();
});
//in your callback route (<MY_CALLBACK_URL>)
window.addEventListener('load', async () => {
const redirectResult = await auth0.handleRedirectCallback();
//logged in. you can get the user profile like this:
const user = await auth0.getUser();
console.log(user);
});
//with promises
//redirect to the Universal Login Page
document.getElementById('login').addEventListener('click', () => {
auth0.loginWithRedirect().catch(() => {
//error while redirecting the user
});
});
//in your callback route (<MY_CALLBACK_URL>)
window.addEventListener('load', () => {
auth0.handleRedirectCallback().then(redirectResult => {
//logged in. you can get the user profile like this:
auth0.getUser().then(user => {
console.log(user);
});
});
});
<button id="call-api">Call an API</button>
//with async/await
document.getElementById('call-api').addEventListener('click', async () => {
const accessToken = await auth0.getTokenSilently();
const result = await fetch('https://myapi.com', {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`
}
});
const data = await result.json();
console.log(data);
});
//with promises
document.getElementById('call-api').addEventListener('click', () => {
auth0
.getTokenSilently()
.then(accessToken =>
fetch('https://myapi.com', {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`
}
})
)
.then(result => result.json())
.then(data => {
console.log(data);
});
});
<button id="logout">Logout</button>
import createAuth0Client from '@auth0/auth0-spa-js';
document.getElementById('logout').addEventListener('click', () => {
auth0.logout();
});
You can redirect users back to your app after logging out. This URL must appear in the Allowed Logout URLs setting for the app in your Auth0 Dashboard:
auth0.logout({
returnTo: 'https://your.custom.url.example.com/'
});
The SDK can be configured to cache ID tokens and access tokens either in memory or in local storage. The default is in memory. This setting can be controlled using the cacheLocation
option when creating the Auth0 client.
To use the in-memory mode, no additional options need are required as this is the default setting. To configure the SDK to cache data using local storage, set cacheLocation
as follows:
await createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>',
cacheLocation: 'localstorage' // valid values are: 'memory' or 'localstorage'
});
Important: This feature will allow the caching of data such as ID and access tokens to be stored in local storage. Exercising this option changes the security characteristics of your application and should not be used lightly. Extra care should be taken to mitigate against XSS attacks and minimize the risk of tokens being stolen from local storage.
The SDK can be configured to use a custom cache store that is implemented by your application. This is useful if you are using this SDK in an environment where more secure token storage is available, such as potentially a hybrid mobile app.
To do this, provide an object to the cache
property of the SDK configuration.
The object should implement the following functions. Note that all of these functions can optionally return a Promise or a static value.
Signature | Return type | Description |
---|---|---|
get(key) | Promise or object | Returns the item from the cache with the specified key, or undefined if it was not found |
set(key: string, object: any) | Promise or void | Sets an item into the cache |
remove(key) | Promise or void | Removes a single item from the cache at the specified key, or no-op if the item was not found |
allKeys() | Promise<string[]> or string [] | (optional) Implement this if your cache has the ability to return a list of all keys. Otherwise, the SDK internally records its own key manifest using your cache. Note: if you only want to ensure you only return keys used by this SDK, the keys we use are prefixed with @@auth0spajs@@ |
Here's an example of a custom cache implementation that uses sessionStorage
to store tokens and apply it to the Auth0 SPA SDK:
const sessionStorageCache = {
get: function (key) {
return JSON.parse(sessionStorage.getItem(key));
},
set: function (key, value) {
sessionStorage.setItem(key, JSON.stringify(value));
},
remove: function (key) {
sessionStorage.removeItem(key);
},
// Optional
allKeys: function () {
return Object.keys(sessionStorage);
}
};
await createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>',
cache: sessionStorageCache
});
Note: The cache
property takes precedence over the cacheLocation
property if both are set. A warning is displayed in the console if this scenario occurs.
We also export the internal InMemoryCache
and LocalStorageCache
implementations, so you can wrap your custom cache around these implementations if you wish.
Refresh tokens can be used to request new access tokens. Read more about how our refresh tokens work for browser-based applications to help you decide whether or not you need to use them.
To enable the use of refresh tokens, set the useRefreshTokens
option to true
:
await createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>',
useRefreshTokens: true
});
Using this setting will cause the SDK to automatically send the offline_access
scope to the authorization server. Refresh tokens will then be used to exchange for new access tokens instead of using a hidden iframe, and calls the /oauth/token
endpoint directly. This means that in most cases the SDK does not rely on third-party cookies when using refresh tokens.
Note This configuration option requires Rotating Refresh Tokens to be enabled for your Auth0 Tenant.
In all cases where a refresh token is not available, the SDK falls back to the legacy technique of using a hidden iframe with prompt=none
to try and get a new access token and refresh token. This scenario would occur for example if you are using the in-memory cache and you have refreshed the page. In this case, any refresh token that was stored previously would be lost.
If the fallback mechanism fails, a login_required
error will be thrown and could be handled in order to put the user back through the authentication process.
Note: This fallback mechanism does still require access to the Auth0 session cookie, so if third-party cookies are being blocked then this fallback will not work and the user must re-authenticate in order to get a new refresh token.
Organizations is a set of features that provide better support for developers who build and maintain SaaS and Business-to-Business (B2B) applications.
Log in to an organization by specifying the organization
parameter when setting up the client:
createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>',
organization: '<MY_ORG_ID>'
});
You can also specify the organization when logging in:
// Using a redirect
client.loginWithRedirect({
organization: '<MY_ORG_ID>'
});
// Using a popup window
client.loginWithPopup({
organization: '<MY_ORG_ID>'
});
Accept a user invitation through the SDK by creating a route within your application that can handle the user invitation URL, and log the user in by passing the organization
and invitation
parameters from this URL. You can either use loginWithRedirect
or loginWithPopup
as needed.
const url = new URL(invitationUrl);
const params = new URLSearchParams(url.search);
const organization = params.get('organization');
const invitation = params.get('invitation');
if (organization && invitation) {
client.loginWithRedirect({
organization,
invitation
});
}
Advanced options can be set by specifying the advancedOptions
property when configuring Auth0Client
. Learn about the complete set of advanced options in the API documentation
createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
advancedOptions: {
defaultScope: 'email' // change the scopes that are applied to every authz request. **Note**: `openid` is always specified regardless of this setting
}
});
We appreciate feedback and contribution to this repo! Before you get started, please see the following:
For support or to provide feedback, please raise an issue on our issue tracker.
For a rundown of common issues you might encounter when using the SDK, please check out the FAQ.
Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
Auth0 helps you to easily:
This project is licensed under the MIT license. See the LICENSE file for more info.
v1.18.0 (2021-09-15)
Added
Changed
Fixed
FAQs
Auth0 SDK for Single Page Applications using Authorization Code Grant Flow with PKCE
The npm package @auth0/auth0-spa-js receives a total of 524,250 weekly downloads. As such, @auth0/auth0-spa-js popularity was classified as popular.
We found that @auth0/auth0-spa-js demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 45 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.