Why is authentication lost after refreshing my single page application?

Question: Why is authentication lost after refreshing my SPA?

Answer:

There could be a few different reasons why authentication is lost after refreshing a single page application. Common reasons are 1) Auth0 developer keys are being used instead of your own credentials for a social connection or 2) the browser is blocking third-party cookies.

1) Social connection settings

To figure out which problem you might be facing, you can check to see if authentication is lost for database connections (i.e., log in with a username/password) or if it only occurs for social connections (such as Google or Facebook).

If it’s only happening with social connections, you can likely resolve the issue by configuring the social connection to use your own credentials. You can find instructions on connecting to social identity providers here: Social Identity Providers

2) Third-party cookies

Another possibility is that the browser is blocking third-party cookies required for silent authentication to take place. You can determine if this is the issue by checking if this problem only occurs in some browsers (such as Safari) but not others (such as Chrome).

By default, the Auth0 SPA SDK will cache authentication data in memory, which does not persist page refreshes in single-page applications. This means that the SDK will need to check with Auth0 to see if the user has a valid session. The SDK will use silent authentication to accomplish this.

Silent authentication requires third-party cookies supplied by Auth0 as the authorization server. However, various browsers, such as Safari, block third-party cookies by default. This means that the Auth0 SPA SDK will not be able to set cookies during authentication.

A workaround for this is to use Refresh Token Rotation and set the cacheLocation to “localstorage” when initializing the Auth0 client.

Note: When using browser storage such as local storage, it is recommended to shorten the Access Token’s life as much as possible and take other measures to prevent cross-site-scripting attacks.

React example:


<Auth0Provider

domain={REACT_APP_AUTH0_DOMAIN}

client_id={REACT_APP_AUTH0_CLIENT_ID}

audience={API_IDENTIFIER}

redirect_uri={window.location.origin}

onRedirectCallback={onRedirectCallback}

useRefreshTokens

cacheLocation="localstorage"

>

JS example:


auth0 = await createAuth0Client({

domain: config.domain,

client_id: config.clientId,

useRefreshTokens: true,

cacheLocation: 'localstorage'

});

Alternatively, you can use Auth0’s Custom Domain functionality as a workaround. This will prevent browsers from blocking Auth0’s cookies.

Supporting Documentation:

Documentation:

Community Topic:

4 Likes