### Start Okta Hosted Login Server from Root
Source: https://github.com/okta/okta-react/blob/master/samples/okta-hosted-login/README.md
This alternative command, executed from the root directory of the cloned repository, starts the Okta Hosted Login example. It's a convenience script provided by the project.
```bash
npm run okta-hosted-login-server
```
--------------------------------
### Install Dependencies with npm
Source: https://github.com/okta/okta-react/blob/master/samples/custom-login/README.md
This command installs all the necessary Node.js dependencies required for the React application to run. It reads the 'package.json' file to fetch and install packages.
```bash
npm install
```
--------------------------------
### PKCE Flow Initialization for Okta with React
Source: https://github.com/okta/okta-react/blob/master/README.md
This example demonstrates the initialization of the OktaAuth instance with PKCE enabled by default and its integration with the Security component for handling the PKCE flow. It also outlines the necessary route setup for the login callback.
```jsx
import { OktaAuth } from '@okta/okta-auth-js';
const oktaAuth = new OktaAuth({
issuer: 'https://{yourOktaDomain}/oauth2/default',
clientId: '{clientId}',
redirectUri: window.location.origin + '/login/callback',
});
class App extends Component {
render() {
return (
);
}
}
```
--------------------------------
### Start React Application with npm
Source: https://github.com/okta/okta-react/blob/master/samples/custom-login/README.md
This command starts the development server for the React application. It compiles the code and makes the application accessible in a web browser, typically at http://localhost:8080.
```bash
npm start
```
--------------------------------
### Start Custom Login Server from Root
Source: https://github.com/okta/okta-react/blob/master/samples/custom-login/README.md
This command provides an alternative way to start the application server from the root directory of the repository. It might be used for more complex build or serving configurations.
```bash
npm run custom-login-server
```
--------------------------------
### Install okta-react using npm
Source: https://github.com/okta/okta-react/blob/master/README.md
Installs the @okta/okta-react package as a dependency for your project. This is the primary step to begin using the Okta React SDK.
```bash
npm install --save @okta/okta-react
```
--------------------------------
### Start Okta React Router DOM v6 HashRouter Sample App
Source: https://github.com/okta/okta-react/blob/master/samples/routing/react-router-dom-v6-hash/README.md
Commands to start the Okta React Router DOM v6 HashRouter sample application, either using yarn workspace or by navigating to the sample directory and running yarn start.
```bash
yarn workspace @okta/samples.react.react-router-dom-v6-hash start
```
```bash
cd ./samples/react-router-dom-v6-hash
yarn start
```
--------------------------------
### Minimal React Router Example
Source: https://github.com/okta/okta-react/blob/master/README.md
A basic setup for routing in a React application using react-router-dom, demonstrating how to define public, protected, and login callback routes. Ensure the '/login/callback' URL is configured in your Okta App settings.
```javascript
// Example setup for routes in App.js
// (Assuming you have configured your Okta Auth SDK instance)
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { Security, SecureRoute, LoginCallback } from '@okta/okta-react';
import HomePage from './pages/HomePage';
import ProtectedPage from './pages/ProtectedPage';
import LoginPage from './pages/LoginPage'; // A component to handle login redirection
const App = () => {
// Your Okta Auth SDK configuration
const oktaAuthConfig = {
issuer: 'https://YOUR_OKTA_DOMAIN/oauth2/default',
clientId: 'YOUR_CLIENT_ID',
redirectUri: window.location.origin + '/login/callback',
scopes: ['openid', 'profile', 'email'],
pkce: true
};
return (
{/* Example login route */}
);
};
export default App;
```
--------------------------------
### Okta Authentication Setup with React Router
Source: https://github.com/okta/okta-react/blob/master/README.md
This example shows how to initialize the OktaAuth instance and integrate it with React Router's useHistory hook for handling authentication redirects and restoring original URIs. It sets up a Security component to manage authentication state and define routes.
```jsx
import { useHistory } from 'react-router-dom';
import { OktaAuth, toRelativeUrl } from '@okta/okta-auth-js';
const oktaAuth = new OktaAuth({
issuer: 'https://{yourOktaDomain}/oauth2/default',
clientId: '{clientId}',
redirectUri: window.location.origin + '/login/callback'
});
export default App = () => {
const history = useHistory();
const customAuthHandler = (oktaAuth) => {
// Redirect to the /login page that has a CustomLoginComponent
// This example is specific to React-Router
history.push('/login');
};
const restoreOriginalUri = async (_oktaAuth, originalUri) => {
history.replace(toRelativeUrl(originalUri || '/', window.location.origin));
};
return (
{/* some routes here */}
);
};
```
--------------------------------
### Install Okta React Router DOM v6 HashRouter Sample App
Source: https://github.com/okta/okta-react/blob/master/samples/routing/react-router-dom-v6-hash/README.md
Instructions for cloning the repository and installing dependencies for the Okta React Router DOM v6 HashRouter sample application using yarn.
```bash
git clone https://github.com/okta/okta-react.git
yarn
```
--------------------------------
### Navigate to Okta Hosted Login Directory
Source: https://github.com/okta/okta-react/blob/master/samples/okta-hosted-login/README.md
This command changes the current directory to the specific 'okta-hosted-login' example within the cloned repository. This is necessary to run the application-specific commands.
```bash
cd samples-js-react/okta-hosted-login
```
--------------------------------
### Install okta-react Peer Dependencies
Source: https://github.com/okta/okta-react/blob/master/README.md
Installs the necessary peer dependencies required for @okta/okta-react to function correctly. This includes React, react-dom, react-router-dom (version 5.x for SecureRoute), and @okta/okta-auth-js (version 5.3.1 or later).
```bash
npm install --save react
npm install --save react-dom
npm install --save react-router-dom
npm install --save @okta/okta-auth-js
```
--------------------------------
### Clone Okta React Samples Repository
Source: https://github.com/okta/okta-react/blob/master/samples/custom-login/README.md
This bash command clones the Okta samples repository which contains various examples, including the custom login application. This is the first step to obtain the project files.
```bash
git clone https://github.com/okta/samples-js-react.git
```
--------------------------------
### Navigate to Custom Login Directory
Source: https://github.com/okta/okta-react/blob/master/samples/custom-login/README.md
This command changes the current directory to the 'custom-login' folder within the cloned repository. This is necessary to access the specific application files and configuration.
```bash
cd samples-js-react/custom-login
```
--------------------------------
### Okta React: API Request with Access Token
Source: https://context7.com/okta/okta-react/llms.txt
This example demonstrates how to retrieve an access token from the Okta authentication state and use it to make authorized GET requests to a protected API endpoint. It includes error handling for API responses and automatically signs out the user if a 401 Unauthorized error is encountered.
```jsx
import React, { useState, useEffect } from 'react';
import { useOktaAuth } from '@okta/okta-react';
const UserDataComponent = () => {
const { authState, oktaAuth } = useOktaAuth();
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const fetchProtectedData = async () => {
if (!authState?.isAuthenticated) {
return;
}
setLoading(true);
setError(null);
try {
const accessToken = authState.accessToken.accessToken;
const response = await fetch('https://api.example.com/user/data', {
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
setData(result);
} catch (err) {
console.error('API error:', err);
setError(err.message);
if (err.message.includes('401')) {
await oktaAuth.signOut();
}
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchProtectedData();
}, [authState?.isAuthenticated]);
if (!authState) {
return
);
};
export default TokenManager;
```
--------------------------------
### Configure Okta Environment Variables
Source: https://github.com/okta/okta-react/blob/master/samples/okta-hosted-login/README.md
This ini file format shows how to set the required Okta environment variables, ISSUER and CLIENT_ID, in a '.testenv' file. These variables are crucial for the application to authenticate with your Okta organization. The `USE_INTERACTION_CODE` variable is specific to Okta's Identity Engine.
```ini
ISSUER=https://yourOktaDomain.com/oauth2/default
CLIENT_ID=123xxxxx123
# For Okta Identity Engine:
# USE_INTERACTION_CODE=true
```
--------------------------------
### Implement Custom Authentication Handler with Okta React
Source: https://context7.com/okta/okta-react/llms.txt
Demonstrates overriding the default authentication behavior using the onAuthRequired callback. It allows for custom login flows and redirects, handling authentication state and user interactions. This example requires @okta/okta-react and react-router-dom.
```jsx
import React from 'react';
import { BrowserRouter as Router, Route, useHistory } from 'react-router-dom';
import { Security, SecureRoute } from '@okta/okta-react';
import { OktaAuth, toRelativeUrl } from '@okta/okta-auth-js';
import CustomLoginForm from './components/CustomLoginForm';
import DashboardPage from './pages/Dashboard';
const oktaAuth = new OktaAuth({
issuer: 'https://dev-123456.okta.com/oauth2/default',
clientId: '0oa2abc3def4GHI5jk6l',
redirectUri: window.location.origin + '/login/callback'
});
function App() {
const history = useHistory();
const restoreOriginalUri = async (_oktaAuth, originalUri) => {
history.replace(toRelativeUrl(originalUri || '/', window.location.origin));
};
const onAuthRequired = async (oktaAuth) => {
const originalUri = toRelativeUrl(window.location.href, window.location.origin);
oktaAuth.setOriginalUri(originalUri);
console.log('Authentication required, redirecting to custom login page');
history.push('/login');
};
const handleCustomLogin = async (username, password) => {
try {
const transaction = await oktaAuth.signInWithCredentials({
username,
password
});
if (transaction.status === 'SUCCESS') {
await oktaAuth.signInWithRedirect({
sessionToken: transaction.sessionToken
});
} else {
console.error('Authentication failed:', transaction.status);
}
} catch (err) {
console.error('Login error:', err);
throw err;
}
};
return (
}
/>
);
}
export default App;
```
--------------------------------
### Configure Okta Environment Variables
Source: https://github.com/okta/okta-react/blob/master/samples/custom-login/README.md
This INI file format shows how to configure essential Okta application details as environment variables. These include the Okta authorization server URL (ISSUER) and the application's unique identifier (CLIENT_ID). The USE_INTERACTION_CODE variable is specific to Okta's Identity Engine.
```ini
ISSUER=https://yourOktaDomain.com/oauth2/default
CLIENT_ID=123xxxxx123
USE_INTERACTION_CODE=true
```
--------------------------------
### Update AuthStateManager Methods
Source: https://github.com/okta/okta-react/blob/master/README.md
Details the migration of `authService`'s auth state management methods to the `oktaAuth.authStateManager` object. This includes changes for updating, getting, and subscribing to auth state changes, along with removed methods.
```javascript
// Replace authService.updateAuthState
oktaAuth.authStateManager.updateAuthState
```
```javascript
// Replace authService.getAuthState
oktaAuth.authStateManager.getAuthState
```
```javascript
// Replace authService.on
oktaAuth.authStateManager.subscribe
```
--------------------------------
### Handle Okta OAuth Callback with LoginCallback Component
Source: https://context7.com/okta/okta-react/llms.txt
Configures the `LoginCallback` component to process OAuth redirects from Okta. It handles token parsing, storage, and redirection, and allows customization of error and loading states using `errorComponent` and `loadingElement`. This setup requires `@okta/okta-react`, `react-router-dom`, and `@okta/okta-auth-js`.
```jsx
import React from 'react';
import { Route, Routes } from 'react-router-dom';
import { Security, LoginCallback } from '@okta/okta-react';
import { OktaAuth } from '@okta/okta-auth-js';
const oktaAuth = new OktaAuth({
issuer: 'https://dev-123456.okta.com/oauth2/default',
clientId: '0oa2abc3def4GHI5jk6l',
redirectUri: window.location.origin + '/login/callback'
});
const CustomErrorComponent = ({ error }) => (
Authentication Error
{error.message}
Please try logging in again or contact support.
);
const LoadingSpinner = (
Authenticating...
);
function App() {
const restoreOriginalUri = async (_oktaAuth, originalUri) => {
window.location.replace(originalUri || '/');
};
const handleAuthResume = () => {
window.location.assign('/login');
};
return (
} />
}
/>
);
}
export default App;
```
--------------------------------
### Resume Authentication Flow with onAuthResume (JSX)
Source: https://github.com/okta/okta-react/blob/master/README.md
Demonstrates how to use the `onAuthResume` prop with the `LoginCallback` component to handle `interaction_required` errors, typically when resuming an authentication flow after an external redirect. This example assumes usage with `react-router` and a custom login route.
```jsx
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import { Security, LoginCallback } from '@okta/okta-react';
import { useHistory } from 'react-router-dom';
// Assume oktaAuth and restoreOriginalUri are configured elsewhere
const oktaAuth = null; // Placeholder
const restoreOriginalUri = null; // Placeholder
const CustomLogin = () =>
Custom Login Component
;
const Protected = () =>
Protected Component
;
const Home = () =>
Home Component
;
const App = () => {
const history = useHistory();
const onAuthResume = async () => {
history.push('/login');
};
return (
} />
);
};
export default App;
```
--------------------------------
### Authenticate API Requests with Access Token (Class Component)
Source: https://github.com/okta/okta-react/blob/master/README.md
This class-based React component demonstrates how to retrieve an access token from Okta and use it to authenticate an API request. It fetches messages from a server endpoint, requiring the token in the 'Authorization' header. Assumes 'isomorphic-fetch' and '@okta/okta-react' are installed.
```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
;
}
});
```
--------------------------------
### Authenticate API Requests with Access Token (Function Component)
Source: https://github.com/okta/okta-react/blob/master/README.md
This function-based React component shows how to use the 'useOktaAuth' hook to get an access token and authenticate an API request. It fetches messages from a server endpoint, including the token in the 'Authorization' header. Requires 'isomorphic-fetch' and '@okta/okta-react'.
```jsx
import fetch from 'isomorphic-fetch';
import React, { useState, useEffect } from 'react';
import { useOktaAuth } from '@okta/okta-react';
export default MessageList = () => {
const { authState } = useOktaAuth();
const [messages, setMessages] = useState(null);
useEffect( () => {
if(authState.isAuthenticated) {
const apiCall = async () => {
try {
const response = await fetch('http://localhost:{serverPort}/api/messages', {
headers: {
Authorization: 'Bearer ' + authState.accessToken.accessToken
}
});
const data = await response.json();
setMessages( data.messages );
} catch (err) {
// handle error as needed
}
}
apiCall();
}
}, [authState] );
if (!messages) return
Loading...
;
const items = messages.map(message =>
{message}
);
return
{items}
;
};
```
--------------------------------
### Protect Routes with SecureRoute and Okta Auth (React Router v5)
Source: https://context7.com/okta/okta-react/llms.txt
The SecureRoute component from @okta/okta-react is used to protect routes that require user authentication within a React application using React Router v5. If a user is not authenticated when attempting to access a SecureRoute, it automatically initiates the Okta authentication flow. This example sets up basic routing with Okta integration.
```jsx
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { Security, SecureRoute, LoginCallback } from '@okta/okta-react';
import { OktaAuth, toRelativeUrl } from '@okta/okta-auth-js';
import HomePage from './pages/Home';
import DashboardPage from './pages/Dashboard';
import SettingsPage from './pages/Settings';
const oktaAuth = new OktaAuth({
issuer: 'https://dev-123456.okta.com/oauth2/default',
clientId: '0oa2abc3def4GHI5jk6l',
redirectUri: window.location.origin + '/login/callback'
});
function App() {
const restoreOriginalUri = async (_oktaAuth, originalUri) => {
window.location.replace(toRelativeUrl(originalUri || '/', window.location.origin));
};
return (
);
}
export default App;
```
--------------------------------
### Inject Auth State into Class Components with withOktaAuth HOC
Source: https://context7.com/okta/okta-react/llms.txt
The withOktaAuth higher-order component (HOC) from @okta/okta-react is used to wrap class-based React components. It injects the `oktaAuth` instance and `authState` object as props, enabling class components to access authentication status and tokens without relying on hooks. This example demonstrates fetching messages after authentication.
```jsx
import React, { Component } from 'react';
import { withOktaAuth } from '@okta/okta-react';
class MessageList extends Component {
constructor(props) {
super(props);
this.state = {
messages: null,
loading: false,
error: null
};
}
async componentDidMount() {
const { authState } = this.props;
if (authState && authState.isAuthenticated) {
await this.fetchMessages();
}
}
async componentDidUpdate(prevProps) {
const { authState } = this.props;
if (authState?.isAuthenticated && !prevProps.authState?.isAuthenticated) {
await this.fetchMessages();
}
}
fetchMessages = async () => {
this.setState({ loading: true });
try {
const response = await fetch('https://api.example.com/messages', {
headers: {
'Authorization': `Bearer ${this.props.authState.accessToken.accessToken}`,
'Content-Type': 'application/json'
}
});
const data = await response.json();
this.setState({ messages: data.messages, loading: false });
} catch (err) {
this.setState({ error: err.message, loading: false });
}
};
render() {
const { authState } = this.props;
const { messages, loading, error } = this.state;
if (!authState) return
Loading...
;
if (!authState.isAuthenticated) return
Please log in
;
if (loading) return
Loading messages...
;
if (error) return
Error: {error}
;
if (!messages) return
No messages
;
return (
{messages.map((message, idx) => (
{message}
))}
);
}
}
export default withOktaAuth(MessageList);
```
--------------------------------
### Configure Okta React Router DOM v6 HashRouter Sample App
Source: https://github.com/okta/okta-react/blob/master/samples/routing/react-router-dom-v6-hash/README.md
Configuration steps for the Okta React Router DOM v6 HashRouter sample app, requiring the creation of a testenv file with client ID and issuer URL.
```env
CLIENT_ID=
ISSUER=
```
--------------------------------
### Configure Security Component with restoreOriginalUri (React Router)
Source: https://github.com/okta/okta-react/blob/master/README.md
Shows how to implement the `restoreOriginalUri` callback for the `Security` component, a requirement since version 5.0. This function is used to decouple `react-router`'s history management from the Okta SDK, ensuring proper redirection after authentication.
```javascript
import React from 'react';
import { Security } from '@okta/okta-react';
import { useHistory } from 'react-router-dom';
import { OktaAuth, toRelativeUrl } from '@okta/okta-auth-js';
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 (
{/* your routes here */}
);
};
export default App;
```
--------------------------------
### Initialize Okta Auth Context with Security Component
Source: https://context7.com/okta/okta-react/llms.txt
The Security component wraps your React application to provide Okta authentication context. It requires an initialized OktaAuth instance and configuration for redirect URIs and authentication handlers. This component is essential for managing authentication state across your application.
```jsx
import React from 'react';
import { BrowserRouter as Router, Route, useHistory } from 'react-router-dom';
import { Security } from '@okta/okta-react';
import { OktaAuth, toRelativeUrl } from '@okta/okta-auth-js';
const oktaAuth = new OktaAuth({
issuer: 'https://dev-123456.okta.com/oauth2/default',
clientId: '0oa2abc3def4GHI5jk6l',
redirectUri: window.location.origin + '/login/callback',
scopes: ['openid', 'profile', 'email'],
pkce: true
});
function App() {
const history = useHistory();
const restoreOriginalUri = async (_oktaAuth, originalUri) => {
history.replace(toRelativeUrl(originalUri || '/', window.location.origin));
};
const customAuthHandler = (oktaAuth) => {
history.push('/login');
};
return (
);
}
export default () => (
);
```
--------------------------------
### Update Security Component with OktaAuth Instance
Source: https://github.com/okta/okta-react/blob/master/README.md
Demonstrates how to update the `` component to explicitly accept an OktaAuth instance, replacing the internal `authService`. This requires initializing `OktaAuth` with configuration and passing it as the `oktaAuth` prop.
```jsx
import { OktaAuth } from '@okta/okta-auth-js';
import { Security } from '@okta/okta-react';
const oktaAuth = new OktaAuth(oidcConfig);
export default () => (
// children component
);
```
--------------------------------
### Create React Router Routes with Class-Based Components
Source: https://github.com/okta/okta-react/blob/master/README.md
This snippet demonstrates how to set up React Router routes using class-based components in a React application integrated with Okta. It utilizes `react-router-dom` and `@okta/okta-react` to define public, protected, and callback routes. Dependencies include `react-router-dom`, `@okta/okta-react`, and `@okta/okta-auth-js`.
```jsx
// 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 (
);
}
}
const AppWithRouterAccess = withRouter(App);
export default class extends Component {
render() {
return ();
}
}
```
--------------------------------
### Create React Router Routes with Function-Based Components
Source: https://github.com/okta/okta-react/blob/master/README.md
This snippet shows how to configure React Router routes using function-based components with Okta integration. It leverages hooks like `useHistory` and components from `react-router-dom`, `@okta/okta-react`, and `@okta/okta-auth-js`. This approach offers a more modern React syntax for setting up routes and authentication.
```jsx
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 (
);
};
const AppWithRouterAccess = () => (
);
export default AppWithRouterAccess;
```
--------------------------------
### Replace AuthService with OktaAuth in useOktaAuth Hook
Source: https://github.com/okta/okta-react/blob/master/README.md
Shows how to adapt the `useOktaAuth` hook when migrating from older versions. The hook now exposes `oktaAuth` instead of `authService`, requiring updates to how you access authentication state and methods within your components.
```jsx
import { useOktaAuth } from '@okta/okta-react';
export default () => {
const { oktaAuth, authState } = useOktaAuth();
// handle rest component logic
};
```
--------------------------------
### Handle Basename with restoreOriginalUri (React Router)
Source: https://github.com/okta/okta-react/blob/master/README.md
Provides an implementation of the `restoreOriginalUri` callback specifically for scenarios where the `basename` prop is used with ``. This ensures that `basename` duplication issues are avoided during URL redirection.
```javascript
import { toRelativeUrl } from '@okta/okta-auth-js';
import { useHistory } from 'react-router-dom';
const history = useHistory(); // Assume history is available
const restoreOriginalUri = async (_oktaAuth, originalUri) => {
const basepath = history.createHref({});
const originalUriWithoutBasepath = originalUri.replace(basepath, '/');
history.replace(toRelativeUrl(originalUriWithoutBasepath, window.location.origin));
};
```
--------------------------------
### Access Tokens using OktaAuth TokenManager
Source: https://github.com/okta/okta-react/blob/master/README.md
Explains how to retrieve tokens after the removal of the `getTokenManager` method. Token data is now accessible via the `tokenManager` property of the `oktaAuth` instance, allowing synchronous access to tokens.
```javascript
const tokens = oktaAuth.tokenManager.getTokens();
```
--------------------------------
### Okta React: Programmatic Login and Custom Authentication Flow
Source: https://context7.com/okta/okta-react/llms.txt
This snippet shows how to programmatically trigger Okta sign-in and sign-out, manage authentication state, and integrate custom login buttons within a React application using the Okta React SDK. It handles redirects and displays user information upon successful authentication.
```jsx
import React, { useState, useEffect } from 'react';
import { useOktaAuth } from '@okta/okta-react';
import { useNavigate } from 'react-router-dom';
const LoginPage = () => {
const { oktaAuth, authState } = useOktaAuth();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
useEffect(() => {
if (authState?.isAuthenticated) {
navigate('/dashboard');
}
}, [authState, navigate]);
const handleLogin = async () => {
setLoading(true);
try {
await oktaAuth.signInWithRedirect({
originalUri: '/dashboard'
});
} catch (err) {
console.error('Login error:', err);
setLoading(false);
}
};
const handleLogout = async () => {
try {
await oktaAuth.signOut({
postLogoutRedirectUri: window.location.origin
});
} catch (err) {
console.error('Logout error:', err);
}
};
if (!authState) {
return
Loading...
;
}
if (authState.isAuthenticated) {
return (
Welcome!
You are logged in as {authState.idToken?.claims.email}
);
}
return (
Welcome to My App
Please sign in to continue
);
};
export default LoginPage;
```
--------------------------------
### Show Login and Logout Buttons with Function-Based Components
Source: https://github.com/okta/okta-react/blob/master/README.md
This snippet demonstrates how to implement login and logout buttons in a function-based React component using the `useOktaAuth` hook. It provides a concise way to access Okta authentication state and functions, allowing for conditional rendering of buttons based on user login status. This approach is suitable for modern React applications utilizing functional components and hooks.
```jsx
// 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
);
}
return (
Logged in!
);
};
export default Home;
```
--------------------------------
### Access Auth State and SDK with useOktaAuth Hook (React)
Source: https://github.com/okta/okta-react/blob/master/README.md
Illustrates how to use the `useOktaAuth` React Hook to access the `authState` object and the `oktaAuth` SDK instance within a functional component. This hook automatically re-renders the component when the authentication state changes.
```javascript
import React from 'react';
import { useOktaAuth } from '@okta/okta-react';
const MyComponent = () => {
const { authState } = useOktaAuth();
if (!authState) {
return
Loading...
;
}
if (authState.isAuthenticated) {
return
Hello User!
;
}
return
You need to login
;
};
export default MyComponent;
```
--------------------------------
### Access Auth State and OktaAuth Instance with useOktaAuth Hook
Source: https://context7.com/okta/okta-react/llms.txt
The useOktaAuth hook allows functional components to access the current authentication state (isAuthenticated, accessToken, idToken, error) and the OktaAuth instance. Components must be descendants of the Security component to use this hook. It facilitates dynamic UI updates based on authentication status and user information retrieval.
```jsx
import React, { useState, useEffect } from 'react';
import { useOktaAuth } from '@okta/okta-react';
const ProfilePage = () => {
const { authState, oktaAuth } = useOktaAuth();
const [userInfo, setUserInfo] = useState(null);
useEffect(() => {
if (!authState || !authState.isAuthenticated) {
setUserInfo(null);
} else {
oktaAuth.getUser().then(info => {
setUserInfo(info);
}).catch(err => {
console.error('Error fetching user info:', err);
});
}
}, [authState, oktaAuth]);
const login = () => oktaAuth.signInWithRedirect();
const logout = () => oktaAuth.signOut('/');
if (!authState) {
return
Loading authentication...
;
}
if (!authState.isAuthenticated) {
return (
Please log in
);
}
return (
User Profile
{userInfo && (
Name: {userInfo.name}
Email: {userInfo.email}
)}
);
};
export default ProfilePage;
```
--------------------------------
### Replace AuthService with OktaAuth in withOktaAuth HOC
Source: https://github.com/okta/okta-react/blob/master/README.md
Illustrates the change required when using the `withOktaAuth` Higher-Order Component (HOC). Props passed to the wrapped component now include `oktaAuth` instead of `authService`, necessitating adjustments in accessing authentication-related properties.
```jsx
import { withOktaAuth } from '@okta/okta-react';
export default withOktaAuth((props) => {
// use props.oktaAuth
});
```
--------------------------------
### Rewrite Logout Logic with OktaAuth signOut Method
Source: https://github.com/okta/okta-react/blob/master/README.md
Details the replacement of the `authService.logout()` method with `oktaAuth.signOut()`. The `signOut` method requires an options object, specifically `postLogoutRedirectUri`, which must be an absolute URL and an allowed URI in your Okta app configuration.
```javascript
authService.logout('/goodbye');
```
```javascript
oktaAuth.signOut({ postLogoutRedirectUri: window.location.origin + '/goodbye' });
```
--------------------------------
### Show Login and Logout Buttons with Class-Based Components
Source: https://github.com/okta/okta-react/blob/master/README.md
This code snippet illustrates how to display login and logout buttons within a class-based React component using the `withOktaAuth` higher-order component. It checks the authentication state provided by `oktaAuth` to conditionally render the appropriate button. This component is typically used for the home page or any entry point where user authentication status needs to be managed.
```jsx
// 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