Choorai
Lv.3 Enterprise

Auth0 Auth Guide

Auth0 is an enterprise-grade authentication platform. Choose it when you need advanced features like RBAC, MFA, and SSO.

Why Auth0?

  • RBAC (Role-Based Access Control) built-in
  • Enterprise SSO (SAML, LDAP) support
  • MFA (Multi-Factor Authentication) easily enabled
  • Detailed login logs and analytics
  • Free tier: 7,000 MAU per month

1Auth0 Project Setup

  1. Create an account at auth0.com
  2. Create a Tenant (e.g., my-app.auth0.com)
  3. ApplicationsCreate Application
  4. Select Single Page Web Applications
  5. Configure the following in Settings:
    • Allowed Callback URLs: http://localhost:5173
    • Allowed Logout URLs: http://localhost:5173
    • Allowed Web Origins: http://localhost:5173

2React App Integration

Terminal
npm install @auth0/auth0-react

Environment Variables

.env.local
# .env.local
VITE_AUTH0_DOMAIN=your-tenant.auth0.com
VITE_AUTH0_CLIENT_ID=your-client-id
VITE_AUTH0_AUDIENCE=https://your-api-identifier

Auth0Provider Setup

main.tsx
// main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';
import './index.css';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.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,
        scope: 'openid profile email',
      }}
    >
      <App />
    </Auth0Provider>
  </React.StrictMode>
);

3Using the useAuth0 Hook

components/AuthButtons.tsx
// components/AuthButtons.tsx
import { useAuth0 } from '@auth0/auth0-react';

export function AuthButtons() {
  const {
    isAuthenticated,
    isLoading,
    user,
    loginWithRedirect,
    logout,
  } = useAuth0();

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (isAuthenticated) {
    return (
      <div className="flex items-center gap-4">
        <img
          src={user?.picture}
          alt={user?.name}
          className="w-10 h-10 rounded-full"
        />
        <span>{user?.name}</span>
        <button
          onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}
          className="px-4 py-2 bg-red-600 text-white rounded-lg"
        >
          Sign Out
        </button>
      </div>
    );
  }

  return (
    <button
      onClick={() => loginWithRedirect()}
      className="px-4 py-2 bg-blue-600 text-white rounded-lg"
    >
      Sign In
    </button>
  );
}

Key Properties/Methods

  • isAuthenticated - Whether user is logged in
  • isLoading - Auth state loading
  • user - User profile info
  • loginWithRedirect() - Redirect to login page
  • logout() - Sign out
  • getAccessTokenSilently() - Obtain API token

4Protected Route Implementation

components/ProtectedRoute.tsx
// components/ProtectedRoute.tsx
import { useAuth0, withAuthenticationRequired } from '@auth0/auth0-react';

// Method 1: Using HOC
export const ProtectedPage = withAuthenticationRequired(
  function Dashboard() {
    const { user } = useAuth0();
    return <div>Welcome, {user?.name}!</div>;
  },
  {
    onRedirecting: () => <div>Redirecting...</div>,
  }
);

// Method 2: Direct check with hook
export function ProtectedContent({ children }: { children: React.ReactNode }) {
  const { isAuthenticated, isLoading, loginWithRedirect } = useAuth0();

  if (isLoading) return <div>Loading...</div>;

  if (!isAuthenticated) {
    loginWithRedirect();
    return <div>Redirecting to login...</div>;
  }

  return <>{children}</>;
}

5Backend API Integration

You need to include the Access Token when making API calls.

hooks/useApi.ts
// hooks/useApi.ts
import { useAuth0 } from '@auth0/auth0-react';

export function useApi() {
  const { getAccessTokenSilently } = useAuth0();

  const fetchWithToken = async (url: string, options: RequestInit = {}) => {
    const token = await getAccessTokenSilently({
      authorizationParams: {
        audience: import.meta.env.VITE_AUTH0_AUDIENCE,
      },
    });

    return fetch(url, {
      ...options,
      headers: {
        ...options.headers,
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });
  };

  return { fetchWithToken };
}

// Usage example
function ProjectList() {
  const { fetchWithToken } = useApi();
  const [projects, setProjects] = useState([]);

  useEffect(() => {
    fetchWithToken('/api/projects')
      .then(res => res.json())
      .then(data => setProjects(data));
  }, []);

  return <ul>{projects.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}

Token Verification on Backend

server.js
// Backend (Node.js/Express example)
import { expressjwt } from 'express-jwt';
import jwksRsa from 'jwks-rsa';

const checkJwt = expressjwt({
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
  }),
  audience: process.env.AUTH0_AUDIENCE,
  issuer: `https://${process.env.AUTH0_DOMAIN}/`,
  algorithms: ['RS256'],
});

// Protected API endpoint
app.get('/api/protected', checkJwt, (req, res) => {
  // Token info is available in req.auth
  res.json({ userId: req.auth.sub });
});

6Role-Based Access Control (RBAC)

Auth0's RBAC feature lets you manage permissions per user.

RBAC Setup
// After creating roles in the Auth0 dashboard,
// add a Rule to include role info in tokens

// Auth0 Rule (configure in Actions or Rules)
exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://your-app.com';
  if (event.authorization) {
    api.idToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
    api.accessToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
  }
};

// Check roles in React
function AdminPanel() {
  const { user, isAuthenticated } = useAuth0();

  const roles = user?.['https://your-app.com/roles'] || [];
  const isAdmin = roles.includes('admin');

  if (!isAdmin) {
    return <div>Admin permission required.</div>;
  }

  return <div>Admin Panel</div>;
}

Info

You can create roles and assign them to users in the Auth0 dashboard under User Management → Roles.

When Should You Choose Auth0?

Auth0 Recommended

  • RBAC/permission management needed
  • Enterprise SSO (SAML) required
  • Detailed login analytics needed
  • MFA is mandatory
  • Compliance requirements (SOC2, HIPAA, etc.)

Consider Alternatives

Next Steps

Last updated: February 22, 2026 · Version: v0.0.1

Send Feedback

Opens a new issue page with your message.

Open GitHub Issue