Browse by type
Okta React SDK builds on top of the Okta Auth SDK.
This SDK is a toolkit to build Okta integration with many common "router" packages, such as react-router, reach-router, and others.
Users migrating from version 1.x of this SDK that required react-router should see Migrating from 1.x to learn what changes are necessary.
With the Okta Auth SDK, you can:
All of these features are supported by this SDK. Additionally, using this SDK, you can:
This SDK does not provide any UI components.
This SDK does not currently support Server Side Rendering (SSR)
This library currently supports:
:heavy_check_mark: The current stable major version series is: 6.x
| Version | Status |
|---|---|
6.x |
:heavy_check_mark: Stable |
5.x |
:heavy_check_mark: Stable |
4.x |
:x: Retired |
3.x |
:x: Retired |
2.x |
:x: Retired |
1.x |
:x: Retired |
The latest release can always be found on the [releases page][github-releases].
This library is available through npm.
Install @okta/okta-react
npm install --save @okta/okta-react
Install peer dependencies
npm install --save react
npm install --save react-dom
npm install --save react-router-dom # see note below
npm install --save @okta/okta-auth-js # requires at least version 5.3.1
⚠️ NOTE ⚠️
The SecureRoute component packaged in this SDK only works with react-router-dom 5.x.
If you're using react-router-dom 6.x, you'll have to write your own SecureRoute component.
See these samples to get started
okta-react provides the means to connect a React SPA with Okta OIDC information. Most commonly, you will connect to a router library such as react-router.
okta-react provides a number of pre-built components to connect a react-router-based SPA to Okta OIDC information. You can use these components directly, or use them as a basis for building your own components.
Route except authentication is needed to render the component.⚠️ NOTE ⚠️
The SecureRoute component packaged in this SDK only works with react-router-dom 5.x.
If you're using react-router-dom 6.x, you'll have to write your own SecureRoute component.
See these samples to get started
okta-react provides the necessary tools to build an integration with most common React-based SPA routers.
<LoginCallback> accepts an optional prop errorComponent that will be used to format the output for any error in handling the callback. This component will be passed an error prop that is an error describing the problem. (see the <OktaError> component for the default rendering)Users of routers other than react-router can use useOktaAuth to see if authState is not null and authState.isAuthenticated is true. If it is false, you can send them to login via oktaAuth.signInWithRedirect(). See the implementation of <LoginCallback> as an example.
These hooks can be used in a component that is a descendant of a Security component (<Security> provides the necessary context). Class-based components can gain access to the same information via the withOktaAuth Higher Order Component, which provides oktaAuth and authState as props to the wrapped component.
oktaAuth - the Okta Auth SDK instance.authState - the AuthState object that shows the current authentication state of the user to your app (initial state is null).This example defines 3 routes:
Note: Make sure you have the /login/callback url (absolute url) added in your Okta App's configuration.
A common mistake is to try and apply an authentication requirement to all pages, THEN add an exception for the login page. This often fails because of how routes are evaluated in most routing packages. To avoid this problem, declare specific routes or branches of routes that require authentication without exceptions.
// src/App.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, withRouter } from 'react-router-dom';
import { SecureRoute, Security, LoginCallback } from '@okta/okta-react';
import { OktaAuth, toRelativeUrl } from '@okta/okta-auth-js';
import Home from './Home';
import Protected from './Protected';
class App extends Component {
constructor(props) {
super(props);
this.oktaAuth = new OktaAuth({
issuer: 'https://{yourOktaDomain}/oauth2/default',
clientId: '{clientId}',
redirectUri: window.location.origin + '/login/callback'
});
this.restoreOriginalUri = async (_oktaAuth, originalUri) => {
props.history.replace(toRelativeUrl(originalUri || '/', window.location.origin));
};
}
render() {
return (
<Security oktaAuth={this.oktaAuth} restoreOriginalUri={this.restoreOriginalUri} >
<Route path='/' exact={true} component={Home} />
<SecureRoute path='/protected' component={Protected} />
<Route path='/login/callback' component={LoginCallback} />
</Security>
);
}
}
const AppWithRouterAccess = withRouter(App);
export default class extends Component {
render() {
return (<Router><AppWithRouterAccess/></Router>);
}
}
import React from 'react';
import { SecureRoute, Security, LoginCallback } from '@okta/okta-react';
import { OktaAuth, toRelativeUrl } from '@okta/okta-auth-js';
import { BrowserRouter as Router, Route, useHistory } from 'react-router-dom';
import Home from './Home';
import Protected from './Protected';
const oktaAuth = new OktaAuth({
issuer: 'https://{yourOktaDomain}/oauth2/default',
clientId: '{clientId}',
redirectUri: window.location.origin + '/login/callback'
});
const App = () => {
const history = useHistory();
const restoreOriginalUri = async (_oktaAuth, originalUri) => {
history.replace(toRelativeUrl(originalUri || '/', window.location.origin));
};
return (
<Security oktaAuth={oktaAuth} restoreOriginalUri={restoreOriginalUri}>
<Route path='/' exact={true} component={Home} />
<SecureRoute path='/protected' component={Protected} />
<Route path='/login/callback' component={LoginCallback} />
</Security>
);
};
const AppWithRouterAccess = () => (
<Router>
<App />
</Router>
);
export default AppWithRouterAccess;
// src/Home.js
import React, { Component } from 'react';
import { withOktaAuth } from '@okta/okta-react';
export default withOktaAuth(class Home extends Component {
constructor(props) {
super(props);
this.login = this.login.bind(this);
this.logout = this.logout.bind(this);
}
async login() {
this.props.oktaAuth.signInWithRedirect();
}
async logout() {
this.props.oktaAuth.signOut('/');
}
render() {
if (!this.props.authState) return
Loading...
;
return this.props.authState.isAuthenticated ?
<button onClick={this.logout}>Logout</button> :
<button onClick={this.login}>Login</button>;
}
});
// src/Home.js
const Home = () => {
const { oktaAuth, authState } = useOktaAuth();
const login = async () => oktaAuth.signInWithRedirect();
const logout = async () => oktaAuth.signOut('/');
if(!authState) {
return
Loading...
;
}
if(!authState.isAuthenticated) {
return (
Not Logged in yet
<button onClick={login}>Login</button>
);
}
return (
Logged in!
<button onClick={logout}>Logout</button>
);
};
export default Home;
When your users are authenticated, your React application has an access token that was issued by your Okta Authorization server. You can use this token to authenticate requests for resources on your server or API. As a hypothetical example, let's say you have an API that provides messages for a user. You could create a MessageList component that gets the access token and uses it to make an authenticated request to your server.
Here is what the React component could look like for this hypothetical example:
```jsx import fetch from 'isomorphic-fetch'; import React, { Component } from 'react'; import { withOktaAuth } from '@okta/okta-react';
export default withOktaAuth(class MessageList extends Component { constructor(props) { super(props) this.state = { messages: null } }
async componentDidMount() { try { const response = await fetch('http://localhost:{serverPort}/api/messages', { headers: { Authorization: 'Bearer ' + this.props.authState.accessToken.accessToken } }); const data = await response.json(); this.setState({ messages: data.messages }); } catch (err) { // handle error as needed } }
render() { if (!this.state.messages) return
Loading...
; const items = this.state.messages.map(message =>
$ claude mcp add okta-react \
-- python -m otcore.mcp_server <graph>