Complete Guide to OAuth 2.0 in React Applications
This comprehensive guide walks you through implementing OAuth 2.0 authentication in React applications, covering everything from initial setup to production deployment.
Prerequisites
- React 18+
- Node.js 16+
- Basic understanding of authentication concepts
Step 1: Project Setup
First, install the necessary dependencies:
npm install @authcompany/react-sdk react-router-dom
Step 2: Configure Authentication Provider
Create an authentication context:
import { createContext, useContext } from 'react';
import { AuthProvider } from '@authcompany/react-sdk';
const AuthContext = createContext();
export function AuthWrapper({ children }) {
return (
<AuthProvider
clientId={process.env.REACT_APP_CLIENT_ID}
domain={process.env.REACT_APP_AUTH_DOMAIN}
redirectUri={window.location.origin + '/callback'}
>
{children}
</AuthProvider>
);
}
Step 3: Implement Protected Routes
Create a protected route component:
import { useAuth } from '@authcompany/react-sdk';
import { Navigate } from 'react-router-dom';
function ProtectedRoute({ children }) {
const { isAuthenticated, isLoading } = useAuth();
if (isLoading) return <div>Loading...</div>;
if (!isAuthenticated) return <Navigate to="/login" />;
return children;
}
Step 4: Add Login/Logout Functionality
Implement authentication controls:
function LoginButton() {
const { loginWithRedirect } = useAuth();
return (
<button onClick={() => loginWithRedirect()}>
Log In
</button>
);
}
function LogoutButton() {
const { logout } = useAuth();
return (
<button onClick={() => logout({ returnTo: window.location.origin })}>
Log Out
</button>
);
}
Step 5: Handle Callback Route
Create a callback component to handle the OAuth redirect:
import { useEffect } from 'react';
import { useAuth } from '@authcompany/react-sdk';
import { useNavigate } from 'react-router-dom';
function CallbackPage() {
const { handleRedirectCallback } = useAuth();
const navigate = useNavigate();
useEffect(() => {
const handleCallback = async () => {
await handleRedirectCallback();
navigate('/dashboard');
};
handleCallback();
}, []);
return <div>Processing authentication...</div>;
}
Security Best Practices
- Always use PKCE for public clients
- Store tokens securely (avoid localStorage)
- Implement proper CORS policies
- Use HTTPS in production
- Validate tokens on the backend
Troubleshooting Common Issues
- Redirect URI mismatch errors
- CORS configuration problems
- Token expiration handling
- State management conflicts
With this implementation, you'll have a secure OAuth 2.0 authentication flow in your React application that follows industry best practices.