I’m trying to use okta-auth-js in a react app (trying to avoid okta-react) and am running into issues with expired tokens. Users are able to authenticate but after timeout, tokens/sessions aren’t being refreshed automatically, resulting in a bunch of 401’s on requests.
const oktaAuth = new OktaAuth({
issuer: '',
clientId: config.OKTA_CLIENT_ID,
redirectUri: config.OKTA_REDIRECT_URI,
pkce: true,
restoreOriginalUri: (oktaAuth, originalUri) => {
sentryBrowserHistory.replace(originalUri);
},
});
export const AuthenticationContext = createContext(null);
const LOGIN_CALLBACK_PATH = '/login/callback';
const AuthenticationProvider = ({ children }) => {
const location = useLocation();
const [isAuthenticated, setIsAuthenticated] = useState(false);
const isHandlingLoginRedirect = location.pathname === LOGIN_CALLBACK_PATH;
const render = () => {
if (isAuthenticated && !isHandlingLoginRedirect) {
return children;
}
};
useEffect(() => {
const checkAuthentication = async () => {
const redirecting = await oktaAuth.isLoginRedirect();
const authenticated = await oktaAuth.isAuthenticated();
if (!authenticated && !redirecting) {
await oktaAuth.clearDPoPStorage();
await oktaAuth.setOriginalUri(location.pathname);
await oktaAuth.signInWithRedirect();
} else if (authenticated) {
setIsAuthenticated(true);
}
};
checkAuthentication();
oktaAuth.authStateManager.subscribe(checkAuthentication);
return () => {
oktaAuth.authStateManager.subscribe(checkAuthentication);
};
}, []);
return (
<AuthenticationContext.Provider value={{ oktaAuth }}>
<Route
path={LOGIN_CALLBACK_PATH}
exact={true}
component={LoginCallbackPage}
/>
{render()}
</AuthenticationContext.Provider>
);
};