Multi-Factor Authentication (MFA)
To implement Multi-Factor Authentication (MFA) in a React application, you can use Auth0 or similar identity providers that support MFA. In this example, I’ll use Auth0 to handle both authentication and MFA. Auth0 provides an easy way to configure and enforce MFA (e.g., with an authenticator app, SMS, or email).
Steps to Implement MFA in React with Auth0
1. Set Up Auth0 for MFA
- Go to your Auth0 Dashboard:
- Navigate to Security > Multi-factor Auth:
- Enable the Push Notifications or One-Time Password (OTP) option.
- Choose a factor to use for MFA, such as Authenticator Apps (e.g., Google Authenticator) or SMS.
- Optionally, set up Adaptive MFA (enforcing MFA based on certain criteria).
- Create an Application:
- Go to Applications > Applications > Create Application.
- Choose Single-Page Application as the type.
- Configure allowed callback URLs, logout URLs, and web origins, usually
http://localhost:3000.
- Note your Domain, Client ID, and Client Secret.
2. Install the Auth0 SDK for React
In your React application directory, install the Auth0 React SDK:
npm install @auth0/auth0-react
3. Set Up Auth0Provider in Your React Application
The Auth0Provider component wraps your app and manages authentication state. Add this to index.js:
- Create a
.envfile in your project’s root directory and add your Auth0 credentials:
REACT_APP_AUTH0_DOMAIN=your-auth0-domain
REACT_APP_AUTH0_CLIENT_ID=your-auth0-client-id
- Configure
Auth0Providerinindex.js:
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Auth0Provider } from '@auth0/auth0-react';
const domain = process.env.REACT_APP_AUTH0_DOMAIN;
const clientId = process.env.REACT_APP_AUTH0_CLIENT_ID;
ReactDOM.render(
<Auth0Provider
domain={domain}
clientId={clientId}
redirectUri={window.location.origin}
>
<App />
</Auth0Provider>,
document.getElementById('root')
);
4. Implement Login with MFA Support in Your Application
Use the useAuth0 hook in your App.js component to handle login and check for MFA enforcement.
// src/App.js
import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';
function App() {
const {
loginWithRedirect,
logout,
isAuthenticated,
user,
isLoading,
} = useAuth0();
if (isLoading) return <div>Loading...</div>;
return (
<div className="App">
<h1>React Multi-Factor Authentication with Auth0</h1>
{isAuthenticated ? (
<div>
<h2>Welcome, {user.name}!</h2>
<button onClick={() => logout({ returnTo: window.location.origin })}>
Log Out
</button>
</div>
) : (
<button onClick={() => loginWithRedirect()}>Log In with MFA</button>
)}
</div>
);
}
export default App;
In this code:
loginWithRedirect: Redirects users to Auth0’s login page, where MFA will be enforced if configured.logout: Logs the user out.
5. Customize the MFA Experience (Optional)
You can customize how MFA is enforced and add custom messages by configuring Auth0’s Universal Login. In the Auth0 Dashboard:
- Go to Branding > Universal Login.
- Customize the login page and MFA prompt as desired.
- Configure custom error messages, branding, and colors to match your application.
6. Run the Application
To test your MFA implementation:
- Start the development server:
npm start
- Open
http://localhost:3000in your browser. - Click Log In with MFA:
- You’ll be redirected to the Auth0 login page.
- After entering your credentials, if MFA is configured (e.g., via an authenticator app or SMS), Auth0 will prompt you to complete MFA.
- Once MFA is successfully completed, you’ll be redirected back to your React app.
Summary
This setup enables Multi-Factor Authentication in a React application with Auth0. By configuring MFA in Auth0, users are required to authenticate with a second factor, adding a layer of security. The Auth0Provider and useAuth0 hook handle the authentication state, making it easy to manage login, logout, and user sessions in the app.
This example can be expanded to include specific routes or components that require MFA verification, giving more flexibility in enforcing MFA as needed.
Single Sign-On (SSO)
Implementing Single Sign-On (SSO) in a React application can be accomplished using protocols like OAuth 2.0 or OpenID Connect (OIDC), commonly supported by identity providers such as Auth0, Okta, or AWS Cognito. For this example, I’ll demonstrate setting up SSO using OAuth 2.0 / OIDC with Auth0, as it provides a user-friendly setup and supports multiple identity providers.
Steps to Implement SSO with Auth0 in a React Application
1. Set Up an Auth0 Account and Application
- Go to Auth0 and create a new account or log in to an existing account.
- Create a new application:
- Choose Single-Page Application as the application type.
- Configure your application:
- Set the Allowed Callback URLs to
http://localhost:3000/callback. - Set the Allowed Logout URLs to
http://localhost:3000. - Set the Allowed Web Origins to
http://localhost:3000.
- Note your Domain, Client ID, and Client Secret—these will be required to set up the connection in your React app.
2. Install the Auth0 SDK for React
In your React app directory, install the Auth0 React SDK:
npm install @auth0/auth0-react
3. Set Up Auth0Provider in Your React Application
The Auth0Provider component wraps the React app and manages authentication state. In your index.js file, configure this provider with your Auth0 credentials.
- Create an Environment Configuration File:
Add your Auth0 credentials in a.envfile in the project root (do not commit this file to version control).
REACT_APP_AUTH0_DOMAIN=your-auth0-domain
REACT_APP_AUTH0_CLIENT_ID=your-auth0-client-id
- Update
index.jsto UseAuth0Provider:
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Auth0Provider } from '@auth0/auth0-react';
const domain = process.env.REACT_APP_AUTH0_DOMAIN;
const clientId = process.env.REACT_APP_AUTH0_CLIENT_ID;
ReactDOM.render(
<Auth0Provider
domain={domain}
clientId={clientId}
redirectUri={window.location.origin}
>
<App />
</Auth0Provider>,
document.getElementById('root')
);
4. Add Login and Logout Functionality
Inside your main App.js component, use the useAuth0 hook to access authentication methods and state.
// src/App.js
import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';
function App() {
const {
loginWithRedirect,
logout,
isAuthenticated,
user,
isLoading,
} = useAuth0();
if (isLoading) return <div>Loading...</div>;
return (
<div className="App">
<h1>React SSO with Auth0</h1>
{isAuthenticated ? (
<div>
<h2>Welcome, {user.name}!</h2>
<button onClick={() => logout({ returnTo: window.location.origin })}>
Log Out
</button>
</div>
) : (
<button onClick={() => loginWithRedirect()}>Log In</button>
)}
</div>
);
}
export default App;
In this example:
loginWithRedirect: Redirects users to the Auth0 login page.logout: Logs users out and redirects them to the specified URL.isAuthenticated: Checks if the user is logged in.user: Provides user information (e.g., name and email).isLoading: Displays a loading indicator until authentication status is known.
5. Protect Routes (Optional)
If you want to protect specific routes in your React app, you can create a ProtectedRoute component to wrap components that should only be accessible to authenticated users.
- Create ProtectedRoute Component:
// src/components/ProtectedRoute.js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { useAuth0 } from '@auth0/auth0-react';
const ProtectedRoute = ({ component: Component, ...rest }) => {
const { isAuthenticated, isLoading } = useAuth0();
if (isLoading) return <div>Loading...</div>;
return (
<Route
{...rest}
render={(props) =>
isAuthenticated ? <Component {...props} /> : <Redirect to="/" />
}
/>
);
};
export default ProtectedRoute;
- Use ProtectedRoute in Your App:
// src/App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import ProtectedRoute from './components/ProtectedRoute';
import { useAuth0 } from '@auth0/auth0-react';
function App() {
const { loginWithRedirect, logout, isAuthenticated, user } = useAuth0();
return (
<Router>
<div className="App">
<h1>React SSO with Auth0</h1>
{isAuthenticated ? (
<div>
<h2>Welcome, {user.name}!</h2>
<button onClick={() => logout({ returnTo: window.location.origin })}>
Log Out
</button>
</div>
) : (
<button onClick={() => loginWithRedirect()}>Log In</button>
)}
<Switch>
<Route exact path="/" component={() => <h2>Home</h2>} />
<ProtectedRoute path="/dashboard" component={() => <h2>Dashboard</h2>} />
</Switch>
</div>
</Router>
);
}
export default App;
In this example:
- Only authenticated users can access the
/dashboardroute, asProtectedRoutewill redirect unauthenticated users to the home page (/).
6. Run the Application
To test the application locally, start the development server:
npm start
When you visit the application at http://localhost:3000, you should see a Log In button. Clicking it redirects you to Auth0’s login page, and upon successful login, you’ll be redirected back to the app with access to the protected content.
Summary
This setup enables SSO for a React application using Auth0. The Auth0Provider wrapper handles authentication, while the useAuth0 hook provides access to authentication functions and state. This method can be expanded to handle role-based access, custom redirects, and more complex authorization flows as needed.
