Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions test/apps/client-js-router-v8-app/.env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Forces Vite to run a development build: https://vitejs.dev/guide/env-and-mode.html#modes
NODE_ENV=development
24 changes: 24 additions & 0 deletions test/apps/client-js-router-v8-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
12 changes: 12 additions & 0 deletions test/apps/client-js-router-v8-app/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>okta-react client-js + React Router v8 sample</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
29 changes: 29 additions & 0 deletions test/apps/client-js-router-v8-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "@okta/test.app.client-js-router-v8-app",
"private": true,
"version": "0.0.0",
"scripts": {
"prestart": "vite build",
"start": "vite preview --port 8080",
"start:dev": "vite build --mode development && vite preview --port 8080",
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router": "^8.3.0",
"@okta/auth-foundation": "*",
"@okta/oauth2-flows": "*",
"@okta/spa-platform": "*",
"@okta/okta-react": "*"
},
"devDependencies": {
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.4",
"@vitejs/plugin-react": "^6.0.5",
"typescript": "^5.6.3",
"vite": "^8.2.1"
}
}
4 changes: 4 additions & 0 deletions test/apps/client-js-router-v8-app/public/resource.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"message": "This is a protected resource, fetched via createFetchLoader.",
"widgets": ["foo", "bar", "baz"]
}
34 changes: 34 additions & 0 deletions test/apps/client-js-router-v8-app/src/ErrorBoundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*!
* Copyright (c) 2017-Present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/

import * as React from 'react';
import { Link, isRouteErrorResponse, useRouteError } from 'react-router';

const ErrorBoundary: React.FC = () => {
const error = useRouteError();

const message = isRouteErrorResponse(error)
? `${error.status} ${error.statusText}`
: error instanceof Error
? error.message
: 'Unknown error';

return (
<div>
<h1>Error</h1>
<p id="error-message">{message}</p>
<Link to="/">Home</Link>
</div>
);
};

export default ErrorBoundary;
59 changes: 59 additions & 0 deletions test/apps/client-js-router-v8-app/src/Home.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*!
* Copyright (c) 2017-Present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/

import * as React from 'react';
import { Link } from 'react-router';
import { Credential } from '@okta/spa-platform';
import { orchestrator, signOutFlow } from './auth';

const Home: React.FC = () => {
const [hasCredential, setHasCredential] = React.useState(false);

React.useEffect(() => {
Credential.getDefault().then((credential) => setHasCredential(credential !== null));
}, []);

const signIn = async () => {
// Redirects to Okta - the returned promise never resolves because the page navigates away.
await orchestrator.getToken();
};

const signOut = async () => {
const credential = await Credential.getDefault();
const idToken = credential?.token.idToken?.toString();
if (!credential || !idToken) {
return;
}
// Ending the Okta session redirect doesn't clear locally stored credentials - that's on the app.
await credential.remove();
const url = await signOutFlow.start(idToken);
window.location.assign(url);
};

return (
<div>
<h1>okta-react client-js + React Router v8 sample</h1>
{hasCredential ? (
<button id="logout-button" onClick={signOut}>Sign out</button>
) : (
<button id="login-button" onClick={signIn}>Sign in</button>
)}
<nav>
<Link to="/protected">Protected</Link>
{' | '}
<Link to="/resource">Resource</Link>
</nav>
</div>
);
};

export default Home;
20 changes: 20 additions & 0 deletions test/apps/client-js-router-v8-app/src/LoginCallback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*!
* Copyright (c) 2017-Present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/

import * as React from 'react';

// This route's loader (createLoginCallbackLoader) always resolves the flow and
// redirects before the router renders a route element, so this is never shown
// except momentarily while the loader is in flight.
const LoginCallback: React.FC = () => <p id="login-callback-loading">Loading...</p>;

export default LoginCallback;
31 changes: 31 additions & 0 deletions test/apps/client-js-router-v8-app/src/Protected.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*!
* Copyright (c) 2017-Present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/

import * as React from 'react';
import { Link, useLoaderData } from 'react-router';
import type { Token } from '@okta/auth-foundation';

const Protected: React.FC = () => {
const token = useLoaderData() as Token;
const claims = token.idToken?.claims;

return (
<div>
<h1>Protected</h1>
<p>Loaded via <code>createTokenLoader</code>.</p>
<pre id="claims">{JSON.stringify(claims, null, 2)}</pre>
<Link to="/">Home</Link>
</div>
);
};

export default Protected;
29 changes: 29 additions & 0 deletions test/apps/client-js-router-v8-app/src/Resource.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*!
* Copyright (c) 2017-Present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/

import * as React from 'react';
import { Link, useLoaderData } from 'react-router';

const Resource: React.FC = () => {
const resource = useLoaderData();

return (
<div>
<h1>Resource</h1>
<p>Loaded via <code>createFetchLoader</code> (<code>/resource.json</code>).</p>
<pre id="resource">{JSON.stringify(resource, null, 2)}</pre>
<Link to="/">Home</Link>
</div>
);
};

export default Resource;
55 changes: 55 additions & 0 deletions test/apps/client-js-router-v8-app/src/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*!
* Copyright (c) 2017-Present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/

import {
OAuth2Client,
AuthorizationCodeFlow,
SessionLogoutFlow,
AuthorizationCodeFlowOrchestrator,
FetchClient,
} from '@okta/spa-platform';

const { ISSUER, CLIENT_ID } = process.env;

export const client = new OAuth2Client({
issuer: ISSUER!,
clientId: CLIENT_ID!,
scopes: ['openid', 'profile', 'email'],
});

export const signInFlow = new AuthorizationCodeFlow(client, {
redirectUri: `${window.location.origin}/login/callback`,
});

export const signOutFlow = new SessionLogoutFlow(client, {
logoutRedirectUri: `${window.location.origin}/`,
});

// `emitBeforeRedirect: false` skips the `login_prompt_required` event - this sample has no
// confirmation UI to gate the redirect on, so `getToken()` should redirect immediately.
export const orchestrator = new AuthorizationCodeFlowOrchestrator(signInFlow, {
emitBeforeRedirect: false,
});

export const fetchClient = new FetchClient(orchestrator);

// If the user abandons a sign-in redirect (e.g. hits the browser back button on Okta's hosted page
// before completing it) and the browser restores this page from the back/forward cache, `signInFlow`
// comes back with `inProgress` still stuck `true` from the aborted attempt - `start()`/`resume()` only
// ever reset it on completion or failure, neither of which runs for an abandoned redirect. That stuck
// state makes every later `orchestrator.getToken()` call throw `flow already in progress` immediately.
// `pageshow`'s `persisted` flag is the standard signal for a bfcache restore, so reset here.
window.addEventListener('pageshow', (event) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was an issue you noticed or something Claude came up with?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran into it by hitting the back button in the middle of the sign in flow, and could not sign in again after that. This is Claude's explanation and fix for it.

if (event.persisted) {
signInFlow.reset();
}
});
33 changes: 33 additions & 0 deletions test/apps/client-js-router-v8-app/src/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*!
* Copyright (c) 2017-Present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/

import * as React from 'react';
import { createRoot } from 'react-dom/client';
import { RouterProvider } from 'react-router';
import { Credential } from '@okta/spa-platform';
import { router } from './router';

if (import.meta.env.DEV) {
// Exposed for manual testing from the browser console, e.g.:
// const cred = await __auth.Credential.getDefault();
// await cred.revoke(); // invalidates the access token server-side
// await cred.refresh(); // forces a refresh attempt (throws: no refresh token in this app's scopes)
(window as unknown as { __auth: unknown }).__auth = { Credential };
}

const container = document.getElementById('root');

createRoot(container!).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);
49 changes: 49 additions & 0 deletions test/apps/client-js-router-v8-app/src/router.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*!
* Copyright (c) 2017-Present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/

import { createBrowserRouter } from 'react-router';
import { createFetchLoader, createLoadersFromOrchestrator } from '@okta/okta-react/client-js';
import { orchestrator, fetchClient } from './auth';
import Home from './Home';
import Protected from './Protected';
import Resource from './Resource';
import LoginCallback from './LoginCallback';
import ErrorBoundary from './ErrorBoundary';

const fetchResource = createFetchLoader(fetchClient);
const { tokenLoader, loginCallbackLoader } = createLoadersFromOrchestrator(orchestrator);

export const router = createBrowserRouter([
{
path: '/',
element: <Home />,
errorElement: <ErrorBoundary />,
},
{
path: '/protected',
element: <Protected />,
loader: () => tokenLoader(),
errorElement: <ErrorBoundary />,
},
{
path: '/resource',
element: <Resource />,
loader: () => fetchResource('/resource.json'),
errorElement: <ErrorBoundary />,
},
{
path: '/login/callback',
element: <LoginCallback />,
loader: loginCallbackLoader,
errorElement: <ErrorBoundary />,
},
]);
Comment on lines +25 to +49

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
export const router = createBrowserRouter([
{
path: '/',
element: <Home />,
errorElement: <ErrorBoundary />,
},
{
path: '/protected',
element: <Protected />,
loader: createTokenLoader(orchestrator),
errorElement: <ErrorBoundary />,
},
{
path: '/resource',
element: <Resource />,
loader: createFetchLoader(fetchClient, () => '/resource.json'),
errorElement: <ErrorBoundary />,
},
{
path: '/login/callback',
element: <LoginCallback />,
loader: createLoginCallbackLoader(orchestrator),
errorElement: <ErrorBoundary />,
},
]);
const tokenLoader = createTokenLoader(orchestrator);
const fetchLoader = createFetchLoader(fetchClient);
const callbackLoader = createLoginCallbackLoader(orchestrator);
export const router = createBrowserRouter([
{
path: '/',
element: <Home />,
errorElement: <ErrorBoundary />,
},
{
path: '/protected',
element: <Protected />,
loader: tokenLoader,
errorElement: <ErrorBoundary />,
},
{
path: '/resource',
element: <Resource />,
loader: fetchLoader('/resource.json'),
errorElement: <ErrorBoundary />,
},
{
path: '/login/callback',
element: <LoginCallback />,
loader: callbackLoader,
errorElement: <ErrorBoundary />,
},
]);

Loading