Authentication

Secure your SonicJS application with JWT authentication and role-based access control.

Overview

SonicJS uses JWT (JSON Web Tokens) for authentication with:

  • 24-hour token expiration
  • HTTP-only cookie storage for web clients
  • Bearer token support for API clients
  • KV-based token caching (5-minute TTL)
  • Role-based access control (RBAC)
  • Permission system for fine-grained access
🔐

JWT Tokens

Secure, stateless authentication with automatic expiration

👥

User Roles

Admin, Editor, Author, and Viewer roles with different permissions

Fast Verification

KV cache for sub-millisecond token verification

🔒

Secure by Default

HTTP-only cookies, CSRF protection, and rate limiting


JWT Authentication

Login

POST/auth/login
Authenticate user and receive JWT token

Login Request

curl -X POST http://localhost:8787/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "admin@sonicjs.com",
    "password": "sonicjs!"
  }'

Response (200 OK):

{
  "user": {
    "id": "admin-user-id",
    "email": "admin@sonicjs.com",
    "username": "admin",
    "firstName": "Admin",
    "lastName": "User",
    "role": "admin"
  },
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Using the Token

Include the token in the Authorization header for authenticated requests:

Authenticated Request

curl http://localhost:8787/admin/content \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

For browser-based applications, the token is automatically stored as an HTTP-only cookie named auth_token.


Passwordless Authentication

SonicJS offers multiple passwordless authentication methods through plugins. These plugins are inactive by default and need to be enabled in the admin panel.

OTP Login Plugin

The OTP (One-Time Password) Login Plugin provides email-based authentication with temporary codes.

Features:

  • Configurable OTP code length (4-8 digits)
  • Code expiration (5-60 minutes, default: 10 minutes)
  • Rate limiting (default: 5 codes per hour)
  • Max verification attempts (default: 3)
  • Optional new user registration support

Installation:

  1. Navigate to AdminPlugins
  2. Find OTP Login plugin
  3. Click Activate
  4. Configure settings:
    • Code Length: 4-8 digits (default: 6)
    • Code Expiration: 5-60 minutes (default: 10)
    • Max Attempts: 3-10 (default: 3)
    • Rate Limit: Codes per hour (default: 5)
    • Allow Registration: Enable if you want new users to register via OTP

API Usage:

OTP Login Flow

# Step 1: Request OTP code
curl -X POST http://localhost:8787/auth/otp/request \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com"
  }'

# Response: { "message": "OTP code sent to email" }

Database Schema:

The OTP plugin creates a new table otp_codes:

CREATE TABLE otp_codes (
  id TEXT PRIMARY KEY,
  user_email TEXT NOT NULL,
  code TEXT NOT NULL,
  expires_at INTEGER NOT NULL,
  attempts INTEGER DEFAULT 0,
  created_at INTEGER DEFAULT (unixepoch())
);

Magic Link Authentication Plugin

The Magic Link Plugin enables passwordless login via email links.

Features:

  • One-click email authentication
  • No password required
  • Secure token-based links
  • Optional user registration

Installation:

  1. Navigate to AdminPlugins
  2. Find Magic Link Auth plugin
  3. Click Activate
  4. Configure email settings (requires Email Plugin)

API Usage:

Magic Link Flow

# Step 1: Request magic link
curl -X POST http://localhost:8787/auth/magic-link/request \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com"
  }'

# Response: { "message": "Magic link sent to email" }

Choosing an Authentication Method

MethodBest ForSecurityUser Experience
Email + PasswordTraditional apps, maximum control⭐⭐⭐⭐Familiar, requires password management
OTP LoginMobile apps, high-security environments⭐⭐⭐⭐⭐Easy, no password needed, limited time
Magic LinkSimplified onboarding, newsletters⭐⭐⭐⭐Seamless, requires email access

Email Plugin Required: Both OTP and Magic Link authentication require the Email Plugin to be configured with a valid email service (e.g., Resend, SendGrid).


User Management

User Registration

POST/auth/register
Create new user account

Register User

curl -X POST http://localhost:8787/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "securepassword123",
    "username": "newuser",
    "firstName": "John",
    "lastName": "Doe"
  }'

RBAC

User Roles

SonicJS supports four built-in roles:

  • Name
    admin
    Type
    string
    Description

    Full system access. Can manage users, content, settings, and plugins.

  • Name
    editor
    Type
    string
    Description

    Content management. Can create, edit, publish, and delete content.

  • Name
    author
    Type
    string
    Description

    Content creation. Can create and edit own content, but not publish.

  • Name
    viewer
    Type
    string
    Description

    Read-only access. Can view content but not modify.

Middleware

Protect routes with authentication and role-based middleware:

Middleware Protection

// Require authentication
app.use('/admin/*', requireAuth())

// Require specific role
app.use('/admin/*', requireRole(['admin', 'editor']))

// Require permission
app.use('/admin/settings/*', requirePermission('manage:settings'))

// Optional authentication
app.use('/api/*', optionalAuth())

Next Steps

Was this page helpful?