The Okta Embedded Widget (OEW) lets you embed Okta’s sign-in and sign-up flows directly into your web application, so users never have to leave your site to authenticate.
Here’s a basic React example demonstrating how to integrate OEW. First, ensure you have the @okta/okta-signin-widget package installed:
npm install @okta/okta-signin-widget
Then, in your React component (e.g., SignInWidget.js):
import React, { useEffect, useRef } from 'react';
import OktaSignIn from '@okta/okta-signin-widget';
import '@okta/okta-signin-widget/dist/css/okta-sign-in.min.css';
const SignInWidget = () => {
const widgetContainerRef = useRef();
useEffect(() => {
const config = {
baseUrl: 'https://{yourOktaDomain}', // e.g., dev-123456.okta.com
clientId: '{yourClientId}',
redirectUri: window.location.origin + '/login/callback',
authParams: {
scopes: ['openid', 'profile', 'email'],
},
features: {
registration: true, // Enable self-service registration
},
};
const oktaSignIn = new OktaSignIn(config);
oktaSignIn.renderEl({ el: widgetContainerRef.current },
(transaction) => {
// Successful authentication
// The transaction object contains the tokens
// You would typically redirect the user or update your app state here
console.log('Authentication successful:', transaction);
// Example: window.location.href = '/dashboard';
},
(error) => {
// Handle authentication errors
console.error('Authentication error:', error);
}
);
// Cleanup the widget when the component unmounts
return () => oktaSignIn.remove();
}, []); // Empty dependency array ensures this effect runs only once on mount
return <div ref={widgetContainerRef} />;
};
export default SignInWidget;
In your App.js (or similar root component), you’d conditionally render this:
import React from 'react';
import SignInWidget from './SignInWidget'; // Assuming SignInWidget.js is in the same directory
function App() {
const isAuthenticated = false; // Replace with your actual authentication state logic
return (
<div className="App">
{isAuthenticated ? (
<h1>Welcome to your Dashboard!</h1>
) : (
<SignInWidget />
)}
</div>
);
}
export default App;
The baseUrl is your Okta organization’s unique URL, and clientId is obtained from your Okta application’s settings. The redirectUri is where Okta sends the user back after successful authentication.
The OktaSignIn constructor takes a config object. Key parameters include baseUrl, clientId, redirectUri, and authParams for specifying requested scopes (like openid, profile, email). You can also enable features like registration for self-service sign-ups.
The renderEl method mounts the widget into the DOM element provided by widgetContainerRef.current. The callback functions handle successful authentication (receiving a transaction object with tokens) and errors.
Crucially, the useEffect hook with an empty dependency array ensures the widget is initialized only once when the component mounts. The cleanup function returned by useEffect (oktaSignIn.remove()) prevents memory leaks by unmounting the widget when the component unmounts.
The isAuthenticated variable in App.js would typically be managed by your application’s authentication state management system, perhaps using tokens obtained from Okta.
When a user successfully authenticates, the transaction object passed to the success callback contains valuable information, including JWTs (ID token, access token) and session tokens. Your application would then use these tokens to establish a user session, often by storing them securely (e.g., in localStorage or sessionStorage, or via HTTP-only cookies) and making subsequent API requests with the access token.
The OktaSignIn widget is highly customizable. You can pass additional options to renderEl to override default UI elements, localize strings, or configure specific sign-in flows. For instance, to customize the widget’s appearance, you could pass a customCss property to the config object.
The redirectUri must be registered in your Okta application settings. If it’s not, Okta will prevent the redirect, leading to an error.
If you need to handle different authentication flows (e.g., passwordless, social sign-in), you’ll configure those within your Okta application and can then enable them in the OEW configuration.
The scopes in authParams determine the information Okta will include in the ID token. openid is required for OpenID Connect flows. profile grants access to user profile information (name, picture, etc.), and email grants access to the user’s email address.
The features object allows you to enable or disable specific functionalities of the widget. registration: true enables the sign-up link, while rememberMe: true could show a "Remember Me" checkbox.
The transaction object returned upon successful authentication can also contain a state parameter if one was provided in the initial authorization request. This state parameter is crucial for mitigating CSRF attacks and should be validated on the callback.
You can also use the OEW in a pure JavaScript application without a framework like React. The core logic of initializing OktaSignIn and rendering it into a DOM element remains the same.
After integrating the basic sign-in, the next challenge is managing user sessions and protecting your application’s routes.