Create the routes
Typically, an app contains routes that require authentication in order to render. Use the <SecureRoute>
component from Okta React SDK (opens new window) to define authenticated routes for your app. The following are some basic routes that you need to configure for your app:
Default page route
For the default /
page, create a src/Home.jsx
file to provide links to relevant locations in your app.
You need to provide a Login
link to render the Sign-In Widget, a Logout
link to sign-out of your authenticated session, and links to authenticated pages by using the authState
object (see authStateManager
in the Auth JS SDK (opens new window)). The useOktaAuth()
method is a React hook (opens new window) that returns an object containing the authState
and the oktaAuth
instance. This hook triggers the page to rerender whenever authState
is updated.
Login route
This route hosts the Sign-In Widget and redirects the user to the default home page if the user is already signed in.
For example, create a src/Login.jsx
file with the Login route component:
Callback route
The Okta React SDK (opens new window) provides the LoginCallback
(opens new window) component for the callback route. It handles token parsing, token storage, and redirects the user to the /
path. If a <SecureRoute>
triggered the redirect, then the callback is directed to the secured route. See how the callback route component is called from the route definition file (src/App.jsx
) in the Connect the routes section.
Protected route
Create a protected route that is only available to users with a valid accessToken
.
In this /protected
component example, a src/Protected.jsx
file is created to show a basic protected page:
Connect the routes
Rename the src/App.js
file to src/App.jsx
, and include components and routes for your app. The <Security>
component controls the authentication flows, so it requires your OpenID Connect configuration. By default, the @okta/okta-react
library redirects the user to Okta's sign-in page when the user isn't authenticated. In this example, onAuthRequired
is overridden to redirect to the custom sign-in route instead.
Note: This example uses version 5.x of the react-router-dom
module for the useHistory
and Route
objects.
Rename the src/index.js
file to src/index.jsx
and edit the file to call the app within the React DOM.
Start your app
To run and test your app, execute:
Open a browser and navigate to your app.