Authentication
Secure password authentication with JWT tokens and session management
Entity Auth provides secure password authentication with short-lived access tokens (15 minutes) and long-lived refresh tokens. Web clients receive refresh tokens as HTTP-only cookies, while mobile clients store them securely in Keychain.
Security Best Practice
Never store access tokens in localStorage or sessionStorage. Entity Auth SDKs manage tokens securely in memory and handle automatic refresh.
SDK Setup
Web/Node.js:
import { EntityAuthClient, init as initEA } from '@entityauth/auth-client';
initEA({
workspaceTenantId: process.env.NEXT_PUBLIC_ENTITY_AUTH_WORKSPACE_TENANT_ID!,
baseURL: process.env.NEXT_PUBLIC_ENTITY_AUTH_URL,
});
// Automatically connects to configured base (defaults to entity-auth.com)
const auth = new EntityAuthClient();
// Optional: For custom deployments
const customAuth = new EntityAuthClient({
baseURL: 'https://your-custom-domain.com'
});
iOS/macOS:
import EntityKit
let config = EntityAuthConfig(
environment: .production,
workspaceTenantId: "your-tenant-id",
clientIdentifier: "ios-app"
)
let auth = EntityAuthFacade(config: config)
Register
await auth.register({
email: "user@example.com",
password: "secure-password",
});try await auth.register(request: .init(email: "user@example.com", password: "secure-password"))Login
Authenticate users with email and password. Tenant is configured via init/env (not user input); the SDK includes it automatically. The SDK then manages access tokens for subsequent authenticated requests.
const result = await auth.login({
email: "user@example.com",
password: "secure-password",
});
// Returns: { accessToken, userId, sessionId }let facade = EntityAuthFacade(config: EntityAuthConfig(workspaceTenantId: "tenant_123"))
try await facade.login(request: LoginRequest(
email: "user@example.com",
password: "secure-password",
workspaceTenantId: "tenant_123"
))
let snapshot = facade.currentSnapshot()
print(snapshot.userId ?? "anonymous")Token Management
- Access tokens expire after 15 minutes for security
- Web: Refresh tokens stored as HTTP-only
ea_refreshcookies - Mobile: Refresh tokens stored securely in iOS/macOS Keychain
- Auto-refresh: SDKs automatically refresh expired tokens
- Cross-origin mode: Set
EA_CROSS_ORIGIN_COOKIES=true(and optionalEA_COOKIE_DOMAIN) to useSameSite=None; Securerefresh cookies for third-party origins.
Avoid logout on full page reload
Access tokens are kept in memory for security. A hard page reload clears in-memory state; the session is restored on the server using the HTTP-only ea_refresh cookie. Guard protected routes with middleware and/or perform a server-side refresh before rendering to avoid a perceived logout or flicker.
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const refresh = request.cookies.get('ea_refresh');
if (!refresh && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = { matcher: ['/dashboard/:path*'] };See Framework Integration for details.
Token Refresh
Web requests made through auth.fetch() automatically refresh on 401 responses. You can also refresh manually:
await auth.refresh();let facade = EntityAuthFacade(config: EntityAuthConfig(workspaceTenantId: "tenant_123"))
try await facade.refreshTokens()Session Management
Sessions are managed by the platform:
- Web: Use
login,refresh, andlogout. The JS SDK does not expose list/revoke APIs. - Swift: Use
EntityKitsession services as shown below.
Swift:
let facade = EntityAuthFacade(config: EntityAuthConfig(workspaceTenantId: "tenant_123"))
let current = try await facade.sessionService.current()
let sessions = try await facade.sessionService.list(includeRevoked: false)
try await facade.sessionService.revoke(sessionId: "session-id")
try await facade.sessionService.revokeByUser(userId: "user-id")
Logout
await auth.logout();try await auth.logout()Security Features
Enterprise Security
Entity Auth implements multiple security layers: Argon2 password hashing, rate limiting (10 attempts/email/minute), audit logging, device tracking, and secure token storage.
Cross-Origin Setup (Web)
Workspaces have their own allowlist. Localhost origins are pre-seeded; add production domains in the dashboard:
- Dashboard → Setup → Allowed Origins
- Click Add Origin and enter your domain (
https://app.example.com) - The middleware automatically replies with the correct
Access-Control-Allow-Origin
Authentication Flow
Initialize SDK
Set up the Entity Auth client (automatically connects to entity-auth.com).
const auth = new EntityAuthClient();Register or Login
Authenticate users with email/password and tenant ID.
await auth.login({
email: "user@example.com",
password: "secure-password",
});Make Authenticated Requests
Use the SDK's fetch method for automatic token management.
const response = await auth.fetch('/api/protected-endpoint');Handle Token Refresh
SDKs automatically refresh expired tokens and retry failed requests.
Monitor Sessions
Track authentication state and handle remote logout events.
auth.onTokenChange((token) => {
if (token) {
// User authenticated
} else {
// User logged out
}
});See also
- Tenant Onboarding — find your tenant ID and start quickly
- Framework Integration — React/Next.js hooks and providers
- Demo Dashboard Guide — replicate the demo features