Prerequisites

If you don't have a React app, or are new to React, please continue with the React Quickstart guide. It will walk you through the creation of a React app, creating routes, and other application development essentials.

Add an OpenID Connect Client in Okta

In Okta, applications are OpenID Connect clients that can use Okta Authorization servers to authenticate users. Your Okta Org already has a default authorization server, so you just need to create an OIDC client that will use it.

ImplicitCallback - (required) Handles the implicit flow callback. This will parse the tokens and store them automatically.

Create Routes

Here are the minimum requirements for a working example:

/ - Anyone can access the home page

/protected - Protected is only visible to authenticated users

/implicit/callback - This is where auth is handled for you after redirection

// src/App.js

importReact,{Component}from'react';

import{BrowserRouterasRouter,Route}from'react-router-dom';

import{Security,SecureRoute,ImplicitCallback}from'@okta/okta-react';

importHomefrom'./Home';

importProtectedfrom'./Protected';

classAppextendsComponent{

render(){

return(

<Router>

<Securityissuer='https://{yourOktaDomain}.com/oauth2/default'

client_id='{clientId}'

redirect_uri={window.location.origin + '/implicit/callback'}>

<Routepath='/'exact={true}component={Home}/>

<SecureRoutepath='/protected'component={Protected}/>

<Routepath='/implicit/callback'component={ImplicitCallback} />

</Security>

</Router>

);

}

}

exportdefaultApp;

Show Login and Logout Buttons

In the relevant location in your application, you will want to provide Login and Logout buttons for the user. You can show/hide the correct button by using the auth.isAuthenticated() method. For example:

// src/Home.js

importReact,{Component}from'react';

import{withAuth}from'@okta/okta-react';

exportdefaultwithAuth(classHomeextendsComponent{

constructor(props){

super(props);

this.state={authenticated:null};

this.checkAuthentication=this.checkAuthentication.bind(this);

this.checkAuthentication();

}

asynccheckAuthentication(){

constauthenticated=awaitthis.props.auth.isAuthenticated();

if(authenticated!==this.state.authenticated){

this.setState({authenticated});

}

}

componentDidUpdate(){

this.checkAuthentication();

}

render(){

if(this.state.authenticated===null)returnnull;

returnthis.state.authenticated?

<buttononClick={this.props.auth.logout}>Logout</button>:

<buttononClick={this.props.auth.login}>Login</button>;

}

});

Use the Access Token

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:

Reference

Security

Security is the top-most component of okta-react. This is where most of the configuration is provided.

Configuration options

issuer (required) - The OpenId Connect issuer

client_id (required) - The OpenId Connect client_id

redirect_uri (required) - Where the callback handler is hosted

scope(optional): Reserved or custom claims to be returned in the tokens

response_type(optional): Desired token grant types

onAuthRequired (optional)

auth (optional) - Provide an Auth object instead of the options above. This is helpful when integrating okta-react with external libraries that need access to the tokens.

Accepts a callback to make a decision when authentication is required. If this is not supplied, okta-react redirects to Okta. This callback will receive auth and history parameters. This is triggered when:

SecureRoute

SecureRoute ensures that a route is only rendered if the user is authenticated. If the user is not authenticated, it calls onAuthRequired if it exists, otherwise, it redirects to Okta.

ImplicitCallback

ImplicitCallback handles the callback after the redirect. By default, it parses the tokens from the uri, stores them, then redirects to /. If a SecureRoute caused the redirect, then the callback redirects to the secured route.

withAuth

withAuth provides a way for components to make decisions based on auth state. It injects an auth prop into the component.

auth

auth provides methods that allow managing tokens and auth state. All of the methods return Promises.

auth.isAuthenticated()

Returns true or false, depending on whether the user has an active access or id token.

auth.getUser()

Returns the result of the OpenID Connect /userinfo endpoint if an access token exists.

auth.getIdToken()

Retrieves the id token from storage if it exists.

auth.getAccessToken()

Retrieves the access token from storage if it exists.

auth.login(fromUri)

Calls onAuthRequired or redirects to Okta if onAuthRequired is undefined. This method accepts a fromUri parameter to push the user to after successful authentication.

auth.logout(uri)

Terminates the user's session in Okta and clears all stored tokens. Accepts an optional uri parameter to push the user to after logout.