6 Authentication
Anton Nesterov edited this page 2026-11-08 20:25:29 +01:00

Authentication Methods

VSKI supports three main authentication methods:

  1. Email/Password - Traditional username and password authentication
  2. API Keys - For service-to-service authentication
  3. OAuth2 - Third-party identity providers (Google, GitHub, etc.)

Email/Password Authentication

User Login

from vski import VskiClient

async with VskiClient("http://127.0.0.1:3000") as client:
    # Login with email and password (also sets the client token)
    result = await client.auth.login("user@example.com", "password123")
    print(result["token"])   # JWT token
    print(result["user"])    # user record

The login method returns:

  • token: JWT token for authenticated requests
  • user: Full user record including email, name, etc.

Set Authentication Token

client.set_token(result["token"])

# Then use the client normally
user = await client.auth.me()

Get Current User

user = await client.auth.me()
print(user["id"], user["email"], user.get("name"))
print(user.get("verified"))   # email verification status

User Registration

user = await client.auth.register({
    "email": "newuser@example.com",
    "password": "SecurePassword123!",
    "passwordConfirm": "SecurePassword123!",
    "name": "John Doe",
})

Note: Password hashing is handled automatically. The user is created in the configured default auth collection.

Email Verification

Email verification and password-reset endpoints are not exposed by the SDK yet; watch the changelog. The command line bootstrap path for the first account is the /installer page or POST /api/admins/init (see Getting Started).

Admin Authentication

Every deployment has an admin (superuser) account for administrative tasks:

# Login as admin (also sets the client token)
result = await client.admins.auth_with_password(
    "admin@example.com", "password123"
)

# The admin client has access to settings and management endpoints
collections = await client.settings.collections.get_list()

From the command line: vski login stores the admin JWT in ~/.vski/config.json.

Important: Change the default admin password immediately in production!

API Key Authentication

API keys are ideal for service-to-service authentication or worker processes.

Creating API Keys

vski keys create worker --roles service    # raw key printed exactly once
# Admin-only SDK call
api_key = await client.keys.generate({
    "name": "Worker Service",
    "enabled": True,
    "roles": "service",        # comma-separated: admin, service, workflows, plugin
})
print(api_key["key"])    # the actual API key (only shown once)
print(api_key["id"])     # reference ID for the key

Using API Keys

client.set_api_key("vski_...")   # sent as X-API-Key on every request

records = await client.collection("posts").get_list(1, 20)

Managing API Keys

img

OAuth2 Authentication

VSKI supports OAuth2 for third-party identity providers.

Available Providers

methods = await client.auth.list_methods()
print(methods["oauth2"]["providers"])
# [
#   {"name": "google", "displayName": "Google"},
#   {"name": "github", "displayName": "GitHub"},
#   ...other providers
# ]

OAuth2 Flow

# Exchange the authorization code (obtained from the provider's callback)
# for a VSKI JWT token
auth_data = await client.auth.auth_via_oauth2(
    "google",
    "authorization-code-from-callback",
    "http://127.0.0.1:3000/auth/callback",
)
print(auth_data["token"])
print(auth_data["user"])

Note: The OAuth2 flow requires obtaining the authorization code separately from the OAuth provider. The auth_via_oauth2 method exchanges the code for a JWT token.

SSO (Hosted Login / OAuth-like Provider)

Any application can use the VSKI server as its login page with an OAuth-like authorization-code flow; no SDK-side login UI required. The server renders a hosted login page (superusers and auth-collection users both work), then redirects back to your application with a single-use authorization code that you exchange for a standard JWT.

Flow

  1. Your application redirects the user to the hosted login page:

    GET /sso/authorize?redirect_uri=http://127.0.0.1:8080/callback&state=<random>
    
  2. The user signs in on the VSKI-rendered page. On success the server redirects back with a one-time code (valid 60 seconds) and your state echoed back:

    302 http://127.0.0.1:8080/callback?code=<single-use-code>&state=<random>
    
  3. Your application exchanges the code for a token:

    auth = await client.auth.exchange_code(code, redirect_uri)
    client.set_token(auth["token"])
    # auth["user"] carries the logged-in identity (id, email, roles)
    

    The response shape matches /api/auth/login: {token, user}. Always verify the returned state matches the one you sent (CSRF protection); the server passes it through untouched.

After a successful login the server sets an HttpOnly session cookie scoped to /sso, so subsequent authorizations skip the login form entirely (true single sign-on across applications). GET /sso/logout clears it.

Login with an OAuth provider

Enabled OAuth providers appear as buttons on the hosted login page. The whole OAuth client flow runs server-side, with no SPA required:

browser ─ GET /sso/oauth/{provider}?redirect_uri=…&state=…
        └► 302 provider authorize URL (client_id, our callback, scope, server-bound state)
provider ─ user approves, 302 back to /sso/oauth/{provider}/callback?code=…&state=…
        └► server exchanges the code (client_secret, same redirect_uri), links or
           auto-registers the user, sets the SSO session cookie
        └► 302 redirect_uri?code=<single-use sso code>&state=<your state>

From there the app exchanges the code exactly like the password flow (POST /api/auth/exchange). Failures (expired handshake, provider error) bounce back to the login form with the error shown. The provider-facing redirect URI is {PUBLIC_URL or request host}/sso/oauth/{provider}/callback; set PUBLIC_URL when running behind a proxy so the provider registration matches.

Providers are configured as _auth_providers records (name, auth/token/ user-info URLs, client_id, client_secret, enabled) plus an optional scope column; when scope is empty, sensible defaults apply for the built-in seeds (Google, GitHub, GitLab, Facebook, Discord).

Redirect URI Policy

Only registered redirect URIs may receive codes:

  • Loopback callbacks (http://127.0.0.1:any-port/..., http://localhost/...) and the vski:// CLI deeplink are always allowed; they stay on the user's machine.

  • Any other URI must be listed exactly in the _system_settings key sso_allowed_redirects (a JSON array string), managed like any settings record:

    await client.collection("_system_settings").create({
        "key": "sso_allowed_redirects",
        "value": '["https://app.example.com/auth/callback"]',
    })
    

Customizing the Login Page

The pages are embedded in the server binary (Go html/template). To customize, drop a replacement login.html into the templates directory, TEMPLATES_DIR (default <DATA_DIR>/templates), and restart the server. Each *.html file you place there replaces the embedded page of the same name (login.html, logged_out.html, error.html); missing files keep the defaults. Template data for login.html:

Field Value
.Error Error message to display (empty on GET)
.Identity Email pre-fill after a failed submit
.RedirectURI Must be posted back as the redirect_uri field
.State Must be posted back as the state field
.Providers Enabled OAuth providers ({{range .Providers}} → .Name)

The form must POST to /sso/authorize with identity, password, redirect_uri, and state.

CLI Login

The Python CLI uses this flow for browser login:

vski login --browser            # opens the browser, waits on a loopback callback
vski login --browser --no-browser   # prints the URL (SSH/remote)
vski login --browser --method deeplink   # via vski:// (register once: vski login --register-deeplink)

Authentication Middleware

The SDK automatically includes the authentication token in request headers:

client.set_token("your-jwt-token")
# all subsequent requests include:
#   Authorization: Bearer your-jwt-token

client.set_api_key("vski_...")
# all subsequent requests include:
#   X-API-Key: vski_...

Custom Database Authentication

When using multiple databases, scope the client (or a sub-client) to a specific database; auth flows then resolve against that database:

client.set_db("my-database")

# or a database-scoped client that shares the connection
db_client = client.db("my-database")

Per-collection auth (an auth collection other than the default) goes through the collection itself:

result = await client.collection("_users").auth_with_password(
    "user@example.com", "password123"
)

User Collections

Creating Auth Collections

# vski/default/collections.yaml
version: 1
database: default

collections:
  _users:
    type: auth
    fields:
      - {name: email, type: email, required: true}
      - {name: password, type: text, required: true}
      - {name: name, type: text}
      - {name: avatar, type: url}

Auth collections automatically include:

  • id: Unique identifier
  • email: Email address
  • created: Creation timestamp
  • updated: Last update timestamp

Note: The collection's fields define the additional attributes available on user records.

Authentication Errors

from vski import VskiError

try:
    await client.auth.login("user@example.com", "wrong-password")
except VskiError as e:
    if "Invalid credentials" in str(e):
        print("Wrong email or password")
    elif e.status_code == 401:
        print("Unauthorized")

Security Best Practices

  1. Change default admin password: immediately after first setup
  2. Use HTTPS in production: always use secure connections
  3. Rotate API keys: regularly update API keys
  4. Use strong passwords: enforce password complexity requirements
  5. Enable email verification: verify user email addresses
  6. Implement rate limiting: prevent brute force attacks (built in for auth endpoints via AUTH_RATE_LIMIT_PER_HOUR)
  7. Store tokens securely: use secure storage for JWT tokens
  8. Set appropriate token expiration: balance security and user experience
  9. Use the principle of least privilege: give users only the access they need

Token Management

Token Refresh

result = await client.auth.refresh()   # also sets the new token
client.set_token(result["token"])

Token Expiration

# When a token expires, the SDK raises VskiError with status 401
from vski import VskiError

try:
    await client.collection("posts").get_list(1, 20)
except VskiError as e:
    if e.status_code == 401:
        # token expired: re-authenticate
        result = await client.auth.login(email, password)
        client.set_token(result["token"])

Role-Based Access Control (RBAC)

VSKI integrates with collections to implement role-based access:

# a roles lookup collection
collections:
  _roles:
    type: base
    fields:
      - {name: name, type: text, required: true}
      - {name: permissions, type: json}
# assign a role to a user
await client.collection("_users").update("user-id", {"role": "editor"})

Access is enforced by collection rules referencing the role (see Rules and Access Control):

collections:
  posts:
    rules:
      create: "@request.auth.role = 'editor'"
      list: "'editor' in @request.auth.roles OR published = true"

API Endpoints

Method Endpoint Description
POST /api/auth/login Login with email/password
POST /api/auth/register Register new user
POST /api/auth/refresh Refresh JWT token
GET /api/auth/methods List auth providers
GET /api/auth/me Get current user
GET /api/auth/oauth2-login OAuth2 code exchange
POST /api/auth/exchange SSO authorization-code exchange
GET /sso/authorize Hosted SSO login page
POST /sso/authorize SSO login form submit
GET /sso/oauth/{provider} Start OAuth provider login
GET /sso/oauth/{provider}/callback OAuth provider callback
GET /sso/logout Clear SSO session cookie
POST /api/admins/auth-with-password Admin authentication
POST /api/admins/init Initialize first admin
GET /api/admins/has-admins Check if admins exist
GET /api/admins/me Get current admin
POST /api/keys Generate API key
POST /api/collections/{collection}/auth-with-password Collection-specific auth