🔐

Auth0

Universal authentication and authorization platform with social logins, SSO, and MFA.

Authentication95% popularityDocumentation

Features

Universal Login
Social Connections
Multi-factor Authentication
Single Sign-On (SSO)
User Management
Rules & Hooks

Code Example

// Auth0 JavaScript Integration
import { Auth0Client } from '@auth0/auth0-js';

class Auth0Service {
  constructor(domain, clientId) {
    this.auth0 = new Auth0Client({
      domain: domain,
      clientId: clientId,
      redirectUri: window.location.origin,
      responseType: 'token id_token',
      scope: 'openid profile email'
    });
    
    this.handleAuthentication();
  }

  // Login with redirect
  login() {
    this.auth0.authorize();
  }

  // Login with popup
  async loginWithPopup() {
    try {
      await this.auth0.popup.authorize({
        responseType: 'token id_token'
      });
      
      return this.getProfile();
    } catch (error) {
      console.error('Login error:', error);
      throw error;
    }
  }

  // Handle authentication callback
  handleAuthentication() {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult);
      } else if (err) {
        console.error('Authentication error:', err);
      }
    });
  }

  // Set session
  setSession(authResult) {
    const expiresAt = JSON.stringify(
      authResult.expiresIn * 1000 + new Date().getTime()
    );
    
    localStorage.setItem('access_token', authResult.accessToken);
    localStorage.setItem('id_token', authResult.idToken);
    localStorage.setItem('expires_at', expiresAt);
    
    // Trigger authentication state change
    window.dispatchEvent(new CustomEvent('authStateChanged', {
      detail: { authenticated: true }
    }));
  }

  // Logout
  logout() {
    localStorage.removeItem('access_token');
    localStorage.removeItem('id_token');
    localStorage.removeItem('expires_at');
    
    this.auth0.logout({
      returnTo: window.location.origin
    });
  }

  // Check if user is authenticated
  isAuthenticated() {
    const expiresAt = JSON.parse(localStorage.getItem('expires_at') || '0');
    return new Date().getTime() < expiresAt;
  }

  // Get user profile
  getProfile() {
    return new Promise((resolve, reject) => {
      const accessToken = localStorage.getItem('access_token');
      
      if (!accessToken) {
        reject(new Error('No access token found'));
        return;
      }
      
      this.auth0.client.userInfo(accessToken, (err, profile) => {
        if (profile) {
          resolve(profile);
        } else {
          reject(err);
        }
      });
    });
  }

  // Renew session
  renewSession() {
    return new Promise((resolve, reject) => {
      this.auth0.checkSession({}, (err, authResult) => {
        if (authResult && authResult.accessToken && authResult.idToken) {
          this.setSession(authResult);
          resolve(authResult);
        } else {
          reject(err);
        }
      });
    });
  }

  // Get access token
  getAccessToken() {
    return localStorage.getItem('access_token');
  }
}

// Usage
const auth = new Auth0Service(
  'your-domain.auth0.com',
  'your-client-id'
);

// Login button handler
document.getElementById('loginBtn').addEventListener('click', () => {
  auth.login();
});

// Logout button handler
document.getElementById('logoutBtn').addEventListener('click', () => {
  auth.logout();
});

// Check authentication state
if (auth.isAuthenticated()) {
  auth.getProfile().then(profile => {
    console.log('User profile:', profile);
  });
}