Easy to use authentication APIs designed to provide a flexible, secure, and fast integration.
Integrating User Management features into your app is quick and easy. In this guide, we’ll walk you through adding a hosted authentication flow to your application using AuthKit.
In addition to this guide, there are a variety of example apps available to help with your integration.
To get the most out of this guide, you’ll need:
Let’s add the necessary dependencies and configuration in your WorkOS Dashboard.
For a client-only approach, use the authkit-react
library to integrate AuthKit directly into your React application. Start by installing the library to your project via npm
.
npm install @workos-inc/authkit-react
A redirect URI is a callback endpoint that WorkOS will redirect to after a user has authenticated. This endpoint will exchange the authorization code returned by WorkOS for an authenticated User object. We’ll create this endpoint in the next step.
You can set a redirect URI in the Redirects section of the WorkOS Dashboard. While wildcards in your URIs can be used in the staging environment, they and query parameters cannot be used in production.
For the client-only integration, make sure to set the callback URI as the same route where you require auth.
When users sign out of their application, they will be redirected to your app’s homepage which is configured in the same dashboard area.
All login requests must originate at your application for the PKCE code exchange to work properly. In some instances, requests may not begin at your app. For example, some users might bookmark the hosted login page or they might be led directly to the hosted login page when clicking on a password reset link in an email.
In these cases, AuthKit will detect when a login request did not originate at your application and redirect to your application’s login endpoint. This is an endpoint that you define at your application that should call the signIn
method, along with the context
search parameter that may have been included in the request. See the code examples below in part 2 of this guide for more information.
You can configure the initiate login URL from the Redirects section of the WorkOS dashboard.
Since your user’s browser will be making calls to the WorkOS API directly, it is necessary to add your domain to the allow list in your WorkOS Settings. This can be configured in the Configure Sessions dialog on the Authentication page of the WorkOS dashboard.
While building your integration in the Staging environment you should add your local development URL here. In the example below we’re adding localhost:5173
to the list of allowed domains.
The code examples use your staging API keys when signed in
The AuthKitProvider
component will handle the redirect from Hosted AuthKit, refresh the session when needed and provide context for hooks used in the components of your app. Initialize it with your client ID, which you can find in the WorkOS dashboard.
import { AuthKitProvider } from '@workos-inc/authkit-react'; export default function Root() { return ( <AuthKitProvider clientId="client_123456789"> <App /> </AuthKitProvider> ); }
For security reasons, the client-only integration cannot be nested inside an iframe
.
The useAuth
hook will return user information and loading status. It also provides functions to retrieve the access token and sign in and sign out the user.
import * as React from 'react'; import { useAuth } from '@workos-inc/authkit-react'; export default function App() { const { isLoading, user, getAccessToken, signIn, signUp, signOut } = useAuth(); // This `/login` endpoint should be registered on the "Redirects" page of the // WorkOS Dashboard. In a real app, this code would live in a route instead // of in the main <App/> component React.useEffect(() => { if (window.location.pathname === '/login') { const searchParams = new URLSearchParams(window.location.search); const context = searchParams.get('context') ?? undefined; // Redirects to the signIn page with the required context signIn({ context }); } }, [window.location, signIn]); // isLoading is true until WorkOS has determined the user's authentication status if (isLoading) { return <p>... insert cool spinner here ...</p>; } // If user doesn't exist, then the user is signed out if (!user) { return ( <> <button onClick={() => { // Redirects to the signIn page signIn(); }} > Sign in </button> <button onClick={() => { // Redirects to the signUp page signUp(); }} > Sign up </button> </> ); } // Show the logged in view return ( <> <p>Welcome back{user.firstName && `, ${user.firstName}`}</p> <p> <button onClick={async () => { // getAccessToken will return an existing (unexpired) access token, or // obtain a fresh one if necessary const accessToken = await getAccessToken(); console.log(`Making API request with ${accessToken}`); }} > Make API Request </button> </p> <p> <button onClick={() => { signOut(); }} > Sign Out </button> </p> </> ); }
If you have routes that you wish to only be accessible to logged in users, you can use a custom React hook.
import { useAuth } from '@workos-inc/authkit-react'; import { useEffect } from 'react'; import { useLocation } from 'react-router-dom'; type UserOrNull = ReturnType<typeof useAuth>['user']; // redirects to the sign-in page if the user is not signed in export const useUser = (): UserOrNull => { const { user, isLoading, signIn } = useAuth(); const location = useLocation(); useEffect(() => { if (!isLoading && !user) { // Use 'state' to return the user to the current page after signing in signIn({ state: { returnTo: location.pathname } }); } }, [isLoading, user]); return user; };
Then use that hook to protect your mandatory sign in routes.
import { useUser } from '../hooks/use-user'; export default function MyProtectedPage() { const user = useUser(); if (!user) { // Redirect to sign in page return '...'; } return ( <> <p>Welcome back{user.firstName && `, ${user.firstName}`}</p> </> ); }
If you haven’t configured your app’s homepage in the WorkOS dashboard, users will see an error when logging out.
Navigate to the authentication endpoint we created and sign up for an account. You can then sign in with the newly created credentials and see the user listed in the Users section of the WorkOS Dashboard.