Skip to main content

Overview

Cat Web uses Auth0 for secure authentication, providing a seamless login experience with OAuth 2.0 and JWT token management. The application protects routes and API calls using Auth0’s React SDK.

Auth0 Integration

The application wraps the entire app with the Auth0Provider in the main entry point:
src/main.tsx
import { Auth0Provider } from '@auth0/auth0-react';

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <Auth0Provider
      domain={import.meta.env.VITE_AUTH0_DOMAIN}
      clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
      authorizationParams={{
        redirect_uri: window.location.origin,
        audience: import.meta.env.VITE_AUTH0_AUDIENCE,
      }}
    >
      <App />
    </Auth0Provider>
    <ToastContainer />
  </StrictMode>,
)

Environment Variables

The following environment variables are required:
  • VITE_AUTH0_DOMAIN - Your Auth0 tenant domain
  • VITE_AUTH0_CLIENT_ID - Your Auth0 application client ID
  • VITE_AUTH0_AUDIENCE - Your Auth0 API audience identifier

Authentication Flow

1

User Access

When a user attempts to access a protected route, the AuthGuard component checks authentication status.
2

Login Redirect

If not authenticated, the user is shown the Login component with a popup-based login flow.
3

Token Management

After successful authentication, Auth0 manages JWT tokens automatically, including refresh token rotation.
4

Protected Access

Authenticated users can access protected routes and make API calls with their access token.

Login Component

The Login component provides a simple, centered login button that triggers Auth0’s popup authentication:
src/components/Login.tsx
import React from 'react';
import { Button, Container, Box } from '@mui/material';
import { useAuth0 } from '@auth0/auth0-react';

const Login: React.FC = () => {
    const { loginWithPopup } = useAuth0();

    const handleLogin = () => {
        loginWithPopup();
    };

    return (
        <Container maxWidth="sm">
            <Box
                display="flex"
                justifyContent="center"
                alignItems="center"
                minHeight="100vh"
            >
                <Button 
                    variant="contained" 
                    color="primary" 
                    size="large"
                    onClick={handleLogin}
                >
                    Log In
                </Button>
            </Box>
        </Container>
    );
};

Protected Routes with AuthGuard

The AuthGuard component protects routes by checking authentication status before rendering protected content:
src/components/AuthGuard.tsx
import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';
import { CircularProgress, Box } from '@mui/material';
import Login from './Login';

interface AuthGuardProps {
    component: React.ReactElement;
}

const AuthGuard: React.FC<AuthGuardProps> = ({ component }) => {
    const { isAuthenticated, isLoading, error } = useAuth0();

    if (isLoading) {
        return (
            <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
                <CircularProgress />
            </Box>
        );
    }

    if (!isAuthenticated) {
        console.log('User is not authenticated, redirecting to login');
        return <Login />;
    }

    if (error) {
        return <div>Oops... {error.message}</div>;
    }   

    return <>{component}</>;
};

How It Works

While Auth0 checks authentication status, a centered loading spinner is displayed:
if (isLoading) {
    return (
        <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
            <CircularProgress />
        </Box>
    );
}

Logout Functionality

Users can log out from the Dashboard or navigation drawer. The logout function redirects users back to the application origin:
src/pages/Dashboard/Dashboard.tsx
const { user, logout } = useAuth0();

<Button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}>
    Logout
</Button>
The returnTo parameter ensures users are redirected back to your application after logout. Make sure this URL is configured in your Auth0 application’s “Allowed Logout URLs”.

Accessing User Information

The Auth0 hook provides access to user profile information:
const { user, isAuthenticated } = useAuth0();

if (isAuthenticated) {
    console.log(user?.name);  // User's name
    console.log(user?.email); // User's email
}

Security Best Practices

Token Management

Auth0 handles token refresh automatically. Access tokens are stored securely and never exposed in localStorage.

API Protection

All API calls include the JWT token in the Authorization header for server-side validation.

Popup Flow

Using popup authentication provides better UX than redirects while maintaining security.

Error Handling

Authentication errors are gracefully handled and displayed to users.

Next Steps

Dashboard

Learn about the dashboard UI and navigation

API Integration

Discover how API calls use JWT tokens

Build docs developers (and LLMs) love