tokenea-auth-component
v1.2.4
Published
Universal authentication component with WebAuthn Passkeys support
Maintainers
Readme
🔐 Tokenea Auth Component
Un componente React universal para autenticación con WebAuthn Passkeys, basado en la implementación exitosa de Tokenea.
✨ Características
- 🔐 WebAuthn Passkeys: Autenticación biométrica sin contraseñas
- 🎯 Conditional UI: Autocompletado nativo de passkeys
- 📱 Responsive: Diseño adaptativo para móvil y desktop
- 🔄 Flujo progresivo: Registro y login unificados
- 💾 Sistema de recuperación: Códigos, QR y email
- ⚡ Plug & Play: Fácil integración con tu backend PHP existente
🚀 Instalación
npm install @tokenea/auth-component📋 Uso Básico
import TokeneaAuth from '@tokenea/auth-component';
function App() {
const config = {
apiEndpoints: {
registerOptions: '/api/register-options.php',
registerVerify: '/api/register-verify.php',
loginOptions: '/api/login-options.php',
loginVerify: '/api/login-verify.php',
sendReminder: '/api/send-reminder.php' // Opcional
},
rpId: 'tu-dominio.com',
rpName: 'Tu App',
redirectUrls: {
dashboard: '/dashboard'
}
};
const handleSuccess = (result) => {
console.log('✅ Autenticación exitosa:', result);
// Manejar éxito (guardar token, redirigir, etc.)
};
const handleError = (error) => {
console.error('❌ Error:', error);
// Manejar error
};
return (
<TokeneaAuth
config={config}
onSuccess={handleSuccess}
onError={handleError}
onModeChange={(mode) => console.log('Modo:', mode)}
/>
);
}⚙️ Configuración
Configuración Básica
const config = {
// 🔗 Endpoints de tu API PHP (REQUERIDO)
apiEndpoints: {
registerOptions: '/api/register-options.php',
registerVerify: '/api/register-verify.php',
loginOptions: '/api/login-options.php',
loginVerify: '/api/login-verify.php',
sendReminder: '/api/send-reminder.php' // Opcional
},
// 🌐 Configuración WebAuthn (REQUERIDO)
rpId: 'tu-dominio.com',
rpName: 'Tu Aplicación',
// 🔄 URLs de redirección (Opcional)
redirectUrls: {
dashboard: '/dashboard',
login: '/login'
}
};Callbacks
const callbacks = {
// ✅ Éxito en autenticación
onSuccess: (result) => {
// result contiene: { success, token, user, credential }
localStorage.setItem('authToken', result.token);
window.location.href = '/dashboard';
},
// ❌ Error en autenticación
onError: (error) => {
console.error('Error de autenticación:', error);
// Mostrar notificación de error
},
// 🔄 Cambio de modo
onModeChange: (mode) => {
// Modos: 'initial', 'login', 'register', 'recovery-step'
console.log('Modo actual:', mode);
}
};🏗️ Backend PHP
El componente está diseñado para funcionar con tu backend PHP existente. Necesitas estos endpoints:
1. register-options.php
// Generar opciones de registro
POST /api/register-options.php
Body: { "username": "[email protected]", "displayName": "Usuario" }
Response: { "success": true, "options": {...} }2. register-verify.php
// Verificar registro
POST /api/register-verify.php
Body: { "id": "...", "rawId": "...", "response": {...} }
Response: { "success": true, "token": "...", "user": {...} }3. login-options.php
// Generar opciones de login
POST /api/login-options.php
Body: { "username": "[email protected]" } // Opcional para Conditional UI
Response: { "challenge": "...", "allowCredentials": [...] }4. login-verify.php
// Verificar login
POST /api/login-verify.php
Body: { "id": "...", "rawId": "...", "response": {...} }
Response: { "success": true, "token": "...", "user": {...} }🎨 Personalización
Estilos CSS
El componente usa Tailwind CSS. Puedes personalizar los estilos:
/* Personalizar colores primarios */
.tokenea-auth {
--primary-color: #667eea;
--secondary-color: #764ba2;
}
/* Personalizar el contenedor */
.tokenea-auth .container {
max-width: 600px;
border-radius: 20px;
}Temas
const config = {
// ... otras opciones
ui: {
theme: 'dark', // 'light', 'dark', 'auto'
showRecovery: true,
showPasskeyEducation: true,
customStyles: 'mi-tema-personalizado'
}
};🔧 Utilidades Exportadas
import {
base64urlDecode,
base64urlEncode,
isWebAuthnSupported,
isConditionalUISupported,
getDeviceInfo,
apiRequest,
isValidEmail,
getPasswordStrength
} from '@tokenea/auth-component';
// Verificar soporte WebAuthn
if (isWebAuthnSupported()) {
console.log('✅ WebAuthn soportado');
}
// Verificar soporte Conditional UI
const conditionalSupported = await isConditionalUISupported();
console.log('Conditional UI:', conditionalSupported);
// Información del dispositivo
const device = getDeviceInfo();
console.log('Navegador:', device.browser);📱 Compatibilidad
Navegadores Soportados
- ✅ Chrome 67+ - Soporte completo
- ✅ Safari 13+ - Soporte completo
- ✅ Firefox 60+ - Soporte completo
- ✅ Edge 79+ - Soporte completo
- ⚠️ Samsung Internet - Limitado
Dispositivos
- 📱 iOS 16+ - Face ID, Touch ID
- 🤖 Android 9+ - Huella, Face Unlock
- 💻 Windows 10+ - Windows Hello
- 🍎 macOS 13+ - Touch ID
🔍 Debugging
// Habilitar logs detallados
window.TOKENEA_DEBUG = true;
// Los logs aparecerán en la consola:
// 🔵 [base64urlDecode] Input: ...
// 🟢 [base64urlEncode] Output: ...
// 🌐 [API] POST /api/register-options.php
// 📤 [API] Request body: ...
// 📥 [API] Response data: ...🚨 Manejo de Errores
const handleError = (error) => {
switch (error) {
case 'WebAuthn is not supported in this browser':
// Mostrar mensaje de navegador no compatible
break;
case 'Registration cancelled or not authorized':
// Usuario canceló el registro
break;
case 'This credential is already registered':
// Credencial duplicada
break;
default:
// Error genérico
console.error('Error:', error);
}
};📦 Build y Distribución
# Desarrollo
npm run dev
# Build para producción
npm run build
# Preview del build
npm run preview
# Publicar a NPM
npm publish🤝 Contribuir
- Fork el repositorio
- Crea una rama para tu feature (
git checkout -b feature/nueva-funcionalidad) - Commit tus cambios (
git commit -am 'Añadir nueva funcionalidad') - Push a la rama (
git push origin feature/nueva-funcionalidad) - Crea un Pull Request
📄 Licencia
MIT © Tokenea
🆘 Soporte
- 📧 Email: [email protected]
- 🐛 Issues: GitHub Issues
- 📖 Docs: Documentación completa
¡Hecho con ❤️ por el equipo de Tokenea!
