Auth0 SDK for single page applications using Authorization Code Grant Flow with PKCE.
The Auth0 Single Page App SDK is a new JavaScript library for implementing authentication and authorization in single page apps (SPA) with Auth0. It provides a high-level API and handles a lot of the details so you can secure SPAs using best practices while writing less code.The Auth0 SPA SDK handles grant and protocol details, token expiration and renewal, as well as token storage and caching. Under the hood, it implements Universal Login and the Authorization Code Grant Flow with PKCE.The library and API documentation are hosted on GitHub.If you encounter any problems or errors when using the new JavaScript SDK, please read the FAQ to see if your issue is covered there.
First, you’ll need to create a new instance of the Auth0Client client object. Create the Auth0Client instance before rendering or initializing your application. You can do this using either the async/await method, or with promises. You should only create one instance of the client.Using createAuth0Client does a couple of things automatically:
It creates an instance of Auth0Client.
It calls getTokenSilently to refresh the user session.
It suppresses all errors from getTokenSilently, except login_required.
Next, create a button users can click to start logging in:<button id="login">Click to Login</button>Listen for click events on the button you created. When the event occurs, use the desired login method to authenticate the user (loginWithRedirect() in this example). After the user is authenticated, you can retrieve the user profile with the getUser() method.
document.getElementById('login').addEventListener('click', async () => { await auth0.loginWithRedirect({ authorizationParams: { redirect_uri: 'http://localhost:3000/' } }); //logged in. you can get the user profile like this: const user = await auth0.getUser(); console.log(user);});
document.getElementById('login').addEventListener('click', () => { auth0.loginWithRedirect({ authorizationParams: { redirect_uri: 'http://localhost:3000/' } }).then(token => { //logged in. you can get the user profile like this: auth0.getUser().then(user => { console.log(user); }); });});
To call your API, start by getting the user’s . Then use the Access Token in your request. In this example, the getTokenSilently method is used to retrieve the Access Token:<button id="callApi">Call an API</button>
The Auth0 SPA SDK stores tokens in memory by default. However, this does not provide persistence across page refreshes and browser tabs. Instead, you can opt-in to store tokens in local storage by setting the cacheLocation property to localstorage when initializing the SDK. This can help to mitigate some of the effects of browser privacy technology that prevents access to the Auth0 by storing Access Tokens for longer.
Storing tokens in browser local storage provides persistence across page refreshes and browser tabs. However, if an attacker can achieve running JavaScript in the SPA using a cross-site scripting (XSS) attack, they can retrieve the tokens stored in local storage. A vulnerability leading to a successful XSS attack can be either in the SPA source code or in any third-party JavaScript code (such as bootstrap, jQuery, or Google Analytics) included in the SPA.Read more about token storage.
The Auth0 SPA SDK can be configured to use rotating Refresh Tokens to get new access tokens silently. These can be used to bypass browser privacy technology that prevents access to the Auth0 session cookie when authenticating silently, as well as providing built-in reuse detection.Configure the SDK to do this by setting useRefreshTokens to true on initialization:
Copy
Ask AI
const auth0 = await createAuth0Client({ domain: '{yourDomain}', clientId: '{yourClientId}', useRefreshTokens: true});// Request a new access token using a refresh tokenconst token = await auth0.getTokenSilently();
will also need to be configured for your tenant before they can be used in your SPA.Once configured, the SDK will request the offline_access scope during the authorization step. Furthermore, getTokenSilently will then call the /oauth/token endpoint directly to exchange refresh tokens for access tokens.
The SDK will obey the storage configuration when storing refresh tokens. If the SDK has been configured using the default in-memory storage mechanism, refresh tokens will be lost when refreshing the page.
If the user takes longer than the default timeout of 60 seconds to complete the authentication flow, the authentication will be interrupted, and you will need to catch the error in your code to either:Suggest that the user retry and close the popup manually using error.popup.close:
Copy
Ask AI
$('#loginPopup').click(async () => { try { await auth0.loginWithPopup(); } catch {error} if (error instanceof auth0.PopupTimeoutError) { // custom logic to inform user to retry error.popup.close(); }});
Or create a custom popup option in the options object:
Copy
Ask AI
$('#loginPopup').click(async () => { const popup = window.open( '', 'auth0:authorize:popup', 'left=100,top=100,width=400,height=600,resizable' ); try { await auth0.loginWithPopup({ popup }); } catch {error} if (error instanceof auth0.PopupTimeoutError) { // custom logic to inform user to retry error.popup.close(); }});
Get a new Access Token silently using either a hidden iframe and prompt=none, or by using a rotating Refresh Token. Refresh Tokens are used when useRefreshTokens is set to true when configuring the SDK.
Getting an Access Token silently without using Refresh Tokens will not work in browsers that block third-party cookies, such as Safari and Brave. To learn more about the custom domain workaround, read Troubleshoot Renew Tokens When Using Safari.
If in-memory storage (the default) and refresh tokens are used, new tokens are retrieved using a web worker on supported browsers:
Access Tokens can also be retrieved using a popup window. Unlike getTokenSilently, this method of retrieving an Access Token will work in browsers where third-party cookies are blocked by default:
Options may be passed to getTokenSilently that get an Access Token with a different and scope of that which was requested at user authentication time.
This only works when not using Refresh Tokens (useRefreshTokens: false), as a Refresh Token is bound to the particular audience and scope that was requested at user authentication time.
You can get the claims of the authenticated user’s by calling the getIdTokenClaims method:
Copy
Ask AI
$('#getIdTokenClaims').click(async () => { const claims = await auth0.getIdTokenClaims(); // if you need the raw id_token, you can access it // using the __raw property const id_token = claims.__raw;});