Skip to main content
The Royalti.io API supports multiple authentication methods to suit different integration needs. This guide covers all authentication flows, token management, and best practices.

Authentication Methods

The API supports four authentication token types, each identified by prefix:

1. JWT Tokens (Standard Authentication)

The primary authentication method for user-facing applications. Token Prefixes:
  • No specific prefix for JWT tokens
  • Detected by JWT structure (header.payload.signature)
Token Lifecycle:
  • access_token: Valid for 6 hours
  • refresh_token: Valid for 1 day
Use Case: Web applications, mobile apps, standard API integrations

2. Workspace API Keys (RWAK)

Programmatic access scoped to a specific workspace. Token Prefix: RWAK Use Case: Server-to-server integrations, automation scripts, CI/CD pipelines

3. User API Keys (RUAK)

Programmatic access scoped to a specific user within a workspace. Token Prefix: RUAK Use Case: User-specific automation, personal integrations

4. God Keys (GODK)

Super admin system access for platform operations. Token Prefix: GODK Use Case: Platform administration, system maintenance (restricted)
God Keys (GODK) provide unrestricted system access and should only be used by authorized platform administrators. Never share or expose God Keys.

JWT Authentication Flow

The standard authentication flow for most applications.

Step 1: Login

Exchange credentials for a refresh token:
curl -X POST "https://server26-dot-royalti-project.uc.r.appspot.com/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "your_password"
  }'
Response:
{
  "message": "Successful",
  "workspaces": [
    {
      "workspaceId": "7bd60554-4f63-4c62-a5f6-c29c3f67cb2a",
      "name": "My Workspace",
      "status": "active",
      "userType": [["Artist"]],
      "role": "admin"
    }
  ],
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
The refresh token is stored in Redis cache for validation. Keep it secure and use it only to obtain access tokens.

Step 2: Get Access Token

Exchange the refresh token and workspace selection for an access token:
curl -X GET "https://server26-dot-royalti-project.uc.r.appspot.com/auth/authtoken?currentWorkspace=WORKSPACE_ID" \
  -H "Authorization: Bearer YOUR_REFRESH_TOKEN"
Response:
{
  "status": "success",
  "message": "Access token generated for My Workspace",
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}

Step 3: Use Access Token

Include the access token in the Authorization header for all API requests:
Authorization: Bearer YOUR_ACCESS_TOKEN
curl -X GET "https://server26-dot-royalti-project.uc.r.appspot.com/user" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

OAuth Social Authentication

The API supports OAuth login via Google, LinkedIn, and Facebook using Passport.js.

Supported Providers

  • Google OAuth - /auth/google
  • LinkedIn OAuth - /auth/linkedin
  • Facebook OAuth - /auth/facebook

OAuth Flow

1

Initiate OAuth

Redirect users to the provider’s OAuth endpoint:
GET /auth/google
GET /auth/linkedin
GET /auth/facebook
Users will be redirected to the provider’s login page.
2

OAuth Callback

After authentication, the provider redirects to our callback URL:
GET /auth/google/callback
GET /auth/linkedin/callback
GET /auth/facebook/callback
The callback exchanges the OAuth code for a session.
3

Session Cookie

OAuth flows use cookie-based refresh token storage for session management.

Provider Account Linking

Users can link or unlink social providers to their existing account: Get Connected Providers:
GET /auth/social/providers
Authorization: Bearer YOUR_ACCESS_TOKEN
Link a Provider:
POST /auth/social/{provider}/link
Authorization: Bearer YOUR_ACCESS_TOKEN
Unlink a Provider:
DELETE /auth/social/{provider}/unlink
Authorization: Bearer YOUR_ACCESS_TOKEN
Where {provider} is one of: google, facebook, linkedin

Provider Storage

Social provider IDs are stored in the Users table:
  • googleId - Google account identifier
  • linkedinId - LinkedIn account identifier
  • facebookId - Facebook account identifier

API Key Authentication

For programmatic access without user interaction.

Workspace API Keys (RWAK)

Provide access to all resources within a specific workspace. Token Format: RWAK_xxxxxxxxxxxxxxxx Usage:
curl -X GET "https://server26-dot-royalti-project.uc.r.appspot.com/artist" \
  -H "Authorization: Bearer RWAK_xxxxxxxxxxxxxxxx"

User API Keys (RUAK)

Provide access scoped to a specific user’s permissions within a workspace. Token Format: RUAK_xxxxxxxxxxxxxxxx Usage:
curl -X GET "https://server26-dot-royalti-project.uc.r.appspot.com/user" \
  -H "Authorization: Bearer RUAK_xxxxxxxxxxxxxxxx"
API keys don’t expire but can be revoked. Store them securely like passwords. Contact support to generate API keys for your account.

Token Management

Token Validation

The authentication middleware validates tokens in this order:
  1. Check for Authorization: Bearer <token> header
  2. Detect token type by prefix (RWAK, RUAK, GODK) or structure (JWT)
  3. Validate against Redis cache (for JWT) or database (for API keys)
  4. Decode token and lookup associated TenantUser
  5. Populate req.user with user context

Workspace Switching

Users can switch between workspaces without re-authenticating:
GET /auth/authtoken?currentWorkspace=NEW_WORKSPACE_ID
Authorization: Bearer YOUR_REFRESH_TOKEN
This returns a new access token scoped to the selected workspace.

Token Refresh

When an access token expires (after 6 hours):
{
  "error": {
    "status": 401,
    "message": "JWT token expired"
  }
}
Request a new access token using your refresh token:
GET /auth/authtoken?currentWorkspace=YOUR_WORKSPACE_ID
Authorization: Bearer YOUR_REFRESH_TOKEN

Logout

Invalidate your tokens and end the session:
POST /auth/logout
Authorization: Bearer YOUR_ACCESS_TOKEN
This removes the refresh token from Redis cache and invalidates the session.

Multi-Tenant Architecture

All data in Royalti.io is isolated by tenant (workspace).

Tenant Context

  • Every resource has a TenantId foreign key
  • JWT tokens carry activeWorkspace for context
  • All queries are automatically scoped to the active tenant
  • Users can belong to multiple tenants with different roles

Custom Domains

Workspaces can use custom domains via Cloudflare SaaS integration:
  • Custom domain detected in request
  • Authentication middleware maps domain to workspace
  • Automatic tenant context without explicit workspace parameter

Password Management

Forgot Password

Request a password reset:
POST /auth/forgotpassword
Content-Type: application/json

{
  "email": "user@example.com",
  "redirect_url": "https://app.royalti.io/reset-password"
}
Returns a verification token to use with /auth/resetpassword.

Reset Password

Reset password with verification code:
PATCH /auth/resetpassword?code=VERIFICATION_CODE
Authorization: Bearer RESET_TOKEN
Content-Type: application/json

{
  "email": "user@example.com",
  "new_password": "new_secure_password"
}

Set Password

For new users who verified their email:
POST /auth/setpassword
Authorization: Bearer VERIFICATION_TOKEN
Content-Type: application/json

{
  "password": "secure_password_123"
}
Request a passwordless login link:
POST /auth/loginlink
Content-Type: application/json

{
  "email": "user@example.com"
}
A login link will be sent to the user’s email. Clicking the link authenticates the user without a password.

Best Practices

Security

  1. Use HTTPS Only
    • All API requests must use HTTPS
    • Verify SSL certificates in production
    • Never transmit tokens over HTTP
  2. Secure Token Storage
    • Store tokens securely (environment variables, secure vaults)
    • Never commit tokens to version control
    • Use separate tokens for development and production
  3. Token Rotation
    • Implement token refresh logic before expiration
    • Handle 401 errors by refreshing tokens
    • Re-authenticate if refresh token expires
  4. API Key Management
    • Treat API keys like passwords
    • Rotate API keys periodically
    • Revoke unused or compromised keys immediately

Error Handling

Handle authentication errors gracefully:
async function makeAuthenticatedRequest(url, accessToken, refreshToken) {
  let response = await fetch(url, {
    headers: { 'Authorization': `Bearer ${accessToken}` }
  });

  if (response.status === 401) {
    // Token expired, refresh it
    const newToken = await refreshAccessToken(refreshToken);
    response = await fetch(url, {
      headers: { 'Authorization': `Bearer ${newToken}` }
    });
  }

  return response.json();
}

Rate Limiting

The login endpoint is rate limited:
  • 20 requests per 3 minutes per IP address
Implement exponential backoff for rate limit errors.

Authentication Middleware

Protected routes use two middleware layers:
  1. basicAuth - JWT validation, populates req.user
  2. auditMiddleware - Captures user context (userId, role, IP, user agent)
Some endpoints use enhanced authentication:
  • enhancedGodminAuth - Supports both GODK and JWT with isAdmin=true
  • subscriptionMiddleware - Validates plan features and limits

Troubleshooting

Common Issues

401 Unauthorized
  • Token expired - refresh your access token
  • Invalid token - verify token is correct and not corrupted
  • Token not in Redis - re-authenticate to get new tokens
403 Forbidden
  • Insufficient permissions - check user role and workspace access
  • Subscription limitation - verify plan includes requested feature
Invalid Workspace
  • Workspace ID doesn’t exist
  • User not member of workspace
  • Workspace is inactive

Debug Tips

  1. Verify token format and structure
  2. Check token expiration timestamps
  3. Confirm workspace ID is correct
  4. Validate user has required permissions
  5. Check Redis connection for JWT validation

Support

For authentication issues or API key requests: