Your first request in 60 seconds
Everything goes through one endpoint: POST /api/v1/execute. The body names the command you want and its params. That's it.
# 1. Sign up (or skip if you already have an account) curl "https://auth.example.com/api/v1/execute" \ -H "Content-Type: application/json" \ -d '{ "command": "AUTH.SIGNUP", "params": { "email": "you@example.com", "password": "CorrectHorseBatteryStaple!", "display_name": "You" } }' # 2. Log in → you get access_token + refresh_token curl "https://auth.example.com/api/v1/execute" \ -H "Content-Type: application/json" \ -d '{ "command": "AUTH.LOGIN", "params": { "email": "you@example.com", "password": "CorrectHorseBatteryStaple!" } }' # 3. Use the token on any protected command curl "https://auth.example.com/api/v1/execute" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $ACCESS_TOKEN" \ -d '{"command":"USER.ME","params":{}}'
Every response has the same shape
Successes and failures share a single envelope. Your client code only needs to branch on ok.
{
"ok": true,
"command": "USER.ME",
"data": {
"id": "usr_01HX…",
"email": "you@example.com",
"is_superadmin": false
},
"error": null
}
{
"ok": false,
"command": "AUTH.LOGIN",
"data": null,
"error": {
"code": "AUTH_ERROR",
"message": "Invalid credentials"
}
}
Tokens, sessions, refresh
AUTH.LOGIN returns a short-lived access_token (15 min default) and a long-lived refresh_token. Put the access token in the Authorization: Bearer header. When it expires, call AUTH.REFRESH with the refresh token to get a new pair. Risk scoring, MFA, IP allowlists, and rate limits are all enforced by the Flow engine in your admin console — you configure it visually, no code changes.
Authentication commands
Primitives for login, signup, MFA, password resets, and OAuth bridges.
Users
CRUD, role changes, avatar uploads, profile fields. Superadmins get the full list; users get self-service.
Sessions
Every active login is a session record. Revoke per-device or revoke-all on password change.
Teams & RBAC
Multi-tenant workspaces with per-team roles and fine-grained permissions.
Flow engine
Model the auth pipeline visually at /flows on your own server. Every trigger (login, signup, refresh…) runs the enabled flow before the hardcoded path, so you can force MFA, deny by risk, or branch on IP allowlists without redeploying.
Webhooks
HMAC-signed, at-least-once outbound deliveries with automatic retries and a dead-letter view.
Licensing
Software licenses with feature flags, seat counts, expiration, and offline activation. Replaces Keygen / Cryptlex.
All 399 commands
Searchable reference. Click any command to copy its fully-qualified name.
Error codes
Every failure returns one of these in error.code. They're stable — safe to branch on.
| Code | Meaning |
|---|---|
| AUTH_ERROR | Invalid credentials, expired session, or MFA required. |
| TOKEN_EXPIRED | Access token expired — call AUTH.REFRESH with your refresh token. |
| TOKEN_INVALID | Token signature failed or was rotated out. |
| PERMISSION_DENIED | Authenticated, but the user lacks the required role/permission. |
| NOT_FOUND | Referenced resource does not exist or is not visible to the caller. |
| VALIDATION_ERROR | Request body failed schema validation. See message for details. |
| RATE_LIMITED | Too many requests. Back off per the Retry-After header. |
| FLOW_BLOCKED | Your configured flow denied this request — inspect flow.reason. |
| UNKNOWN_COMMAND | Command name not in the registry. Check spelling and case. |
| INTERNAL_ERROR | Bastionary misbehaved. Traces go to the quick start. |
Rate limits
Defaults are generous; tune per-endpoint from the admin dashboard on your own server.
- • AUTH.LOGIN — 10 req / minute per IP (spike-guarded)
- • AUTH.FORGOT_PASSWORD — 3 req / hour per email
- • General /api/v1/execute — 600 req / minute per token
- • Webhook redelivery — 5 attempts, exponential backoff capped at 1h
SDKs
Official SDKs are thin wrappers — they speak the same command envelope. You never lose access to the underlying protocol.
Passkeys & WebAuthn
Bastionary supports FIDO2 passkeys out of the box — Face ID, Touch ID, Windows Hello, and hardware security keys (YubiKey, etc). No password required. Works alongside TOTP MFA or as a standalone auth method.
// 1. Begin registration const begin = await fetch('/api/v1/execute', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ command: 'AUTH.WEBAUTHN_REGISTER_BEGIN' }) }).then(r => r.json()); // 2. Call WebAuthn API with the challenge const cred = await navigator.credentials.create({ publicKey: begin.data.options }); // 3. Complete registration await fetch('/api/v1/execute', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ command: 'AUTH.WEBAUTHN_REGISTER_COMPLETE', credential: cred }) });
Migrating from Auth0
Bastionary uses the same OIDC protocol and JWT structure as Auth0. Most migrations are under an hour — swap the domain, import users, update redirect URIs.
- Export users — Use the Auth0 Management API: GET /api/v2/users?per_page=100. Export email, sub, app_metadata, and user_metadata fields.
- Import users — Call USER.BULK_IMPORT with the exported JSON. Map: sub → external_id, email → email, app_metadata → metadata_json.
- Update OIDC config — Replace your Auth0 domain (yourapp.auth0.com) with your Bastionary server in your application config.
- Swap SDK — Replace auth0 package with @bastionary/sdk. The command surface maps 1:1 for login, signup, token refresh, and MFA.
- Update redirect URIs — In your OAuth app config, update the allowed callback URL to your Bastionary instance. Test the full login → token → verify flow.
Keycloak and Clerk migrations follow the same pattern. Keycloak users: export the realm JSON and use USER.BULK_IMPORT. Clerk users: export via the Clerk Dashboard → Users → Export.
Self-Hosting & Deployment
One command gets you running. PostgreSQL 14+ required. Works on any Linux host, Docker, or Kubernetes.
# Docker one-liner
docker run -d -p 8400:8400 \
-e DATABASE_URL="postgresql+asyncpg://user:pass@host/bastionary" \
-e JWT_SECRET="$(openssl rand -hex 32)" \
-e BASTION_HOST="https://app.yourapp.com" \
bastionary/server:latest
HA setup: Run 2+ gunicorn workers (--workers 4) behind Caddy or nginx. A docker-compose.yml with PostgreSQL + Bastionary + Caddy is included in the repo. For Kubernetes, the service is stateless — scale replicas freely, use a managed PG (RDS, Cloud SQL, Supabase).
Next.js Quickstart
Add Bastionary auth to a Next.js 14+ app using the App Router. Works with Server Components and middleware.
# Install npm install bastionary-js # .env.local NEXT_PUBLIC_BASTIONARY_URL=https://auth.example.com BASTIONARY_APP_ID=your_app_id
import { bastionaryMiddleware } from 'bastionary-js/next' export default bastionaryMiddleware({ publicRoutes: ['/', '/about'], loginUrl: '/login', }) export const config = { matcher: ['/((?!_next|static|favicon).*)'] }
import { handleAuth } from 'bastionary-js/next' export const { GET, POST } = handleAuth()
import { getSession } from 'bastionary-js/next/server' export default async function Dashboard() { const session = await getSession() // { user, access_token } return <div>Hello {session.user.email}</div> }
React SPA Quickstart
Client-side React with Vite or CRA. Token stored in memory (not localStorage) for XSS protection.
# Install
npm install bastionary-js
import { BastionaryProvider } from 'bastionary-js/react' import App from './App' createRoot(document.getElementById('root')!).render( <BastionaryProvider url="https://auth.example.com"> <App /> </BastionaryProvider> )
import { useAuth } from 'bastionary-js/react' function Nav() { const { user, signIn, signOut, isLoading } = useAuth() if (isLoading) return null return user ? <button onClick={signOut}>Sign out {user.email}</button> : <button onClick={() => signIn()}>Sign in</button> }
Python / FastAPI Quickstart
Protect FastAPI routes with Bastionary JWT verification. Zero session storage — stateless verification using the JWKS endpoint.
# Install
pip install bastionary python-jose[cryptography] httpx
import httpx from jose import jwt, JWTError from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer BASTIONARY_URL = "https://auth.example.com" oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token") _jwks_cache = None async def get_jwks(): global _jwks_cache if not _jwks_cache: async with httpx.AsyncClient() as c: r = await c.get(f"{BASTIONARY_URL}/.well-known/jwks.json") _jwks_cache = r.json()["keys"] return _jwks_cache async def require_user(token: str = Depends(oauth2_scheme)): keys = await get_jwks() try: payload = jwt.decode(token, keys, algorithms=["RS256"]) return payload except JWTError: raise HTTPException(status.HTTP_401_UNAUTHORIZED) # Usage: @app.get("/me") async def me(user = Depends(require_user)): return {"sub": user["sub"], "email": user.get("email")}
Go Quickstart
Verify Bastionary JWTs in any Go HTTP server. Uses standard library + golang-jwt/jwt.
# Install
go get github.com/golang-jwt/jwt/v5
go get github.com/MicahParks/keyfunc/v3
package auth import ( "net/http" "strings" keyfunc "github.com/MicahParks/keyfunc/v3" jwt "github.com/golang-jwt/jwt/v5" ) const jwksURL = "https://auth.example.com/.well-known/jwks.json" var jwks, _ = keyfunc.NewDefaultCtx(context.Background(), []string{jwksURL}) func RequireAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { raw := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") token, err := jwt.Parse(raw, jwks.Keyfunc) if err != nil || !token.Valid { http.Error(w, "Unauthorized", 401) return } next.ServeHTTP(w, r) }) }
Social Login Setup
Bastionary acts as an OIDC proxy for upstream identity providers. Configure GitHub, Google, or any OAuth2 provider once — all users land in the same identity store with a unified profile.
POST /api/v1/execute { "command": "OIDC.CLIENT_CREATE", "provider": "github", "client_id": "your_github_client_id", "client_secret": "your_github_client_secret", "redirect_uri": "https://auth.example.com/api/oidc/callback", "scopes": ["user:email"] }Users can link multiple providers to one account. On first social login, a user record is created automatically. Account linking is managed via USER.LINK_PROVIDER / USER.UNLINK_PROVIDER.