Question: How do I use Organizations with the React SDK and maintain user sessions?
With the introduction of Organizations, you can now configure applications to prompt users for an Organization prior to logging them in. Once logged in, however, the React SDK has no knowledge of the user’s Organization relationship, so on a page refresh, this causes Silent Authentication to fail. There are two ways to address this that we’ll cover:
- updating the React SDK to use 1 organization (for use-cases where the application is only related to a single organization)
- updating the React SDK to allow for multiple organizations
Answer:
Since the issue lies with the React SDK not having Organization details when the Auth0Provider
instantiates itself, we’ll show some ways to provide that information.
Recipe 1: Configuring a single Organization in the React SDK
- In index.js add the
organization
to the parameters in theAuth0Provider
passing in theorg_id
<Auth0Provider
domain={config.domain}
clientId={config.clientId}
audience={config.audience}
redirectUri={window.location.origin}
onRedirectCallback={onRedirectCallback}
organization={org_id}
>
<App />
</Auth0Provider>
Recipe 2: Configuring multiple organizations
-
The idea behind this strategy is to save the
org_id
when a user first logs in, save it to localStorage, and then pass it into theAuth0Provider
when it re-renders. -
In App.js we’ll grab the
org_id
of the newly authenticated user and save it to localStorage:
//put this above the return in App.js
if ( user && user.org_id) {
localStorage.setItem('orgId', user.org_id);
}
- in index.js we’ll add a function to get the
org_id
and pass it into theAuth0Provider
:
const getOrgId = () =>
{
return localStorage.getItem( 'orgId' );
};
ReactDOM.render(
<Auth0Provider
domain={config.domain}
clientId={config.clientId}
audience={config.audience}
redirectUri={window.location.origin}
onRedirectCallback={onRedirectCallback}
organization={getOrgId() === null ? undefined : getOrgId()}
>
<App />
</Auth0Provider>,
document.getElementById("root")
);
Supporting Documentation:
Documentation: Organizations React SDK