Skip to content

Managing OAuth Applications ​

This guide covers how to register, configure, and manage OAuth applications for WeTrials integration.

Application Registration ​

Prerequisites ​

Before registering an OAuth application, you need:

  • A WeTrials developer account
  • Your application's basic information (name, description, website)
  • Redirect URIs for OAuth callbacks
  • Contact email for security notifications

Registration Process ​

Note

Currently, OAuth application registration requires contacting the WeTrials team. Self-service registration is coming soon.

To register a new OAuth application:

  1. Contact WeTrials Developer Support

  2. Provide Application Details

    json
    {
      "name": "Your Application Name",
      "description": "Brief description of your application",
      "website": "https://yourapp.com",
      "redirect_uris": ["https://yourapp.com/callback", "https://yourapp.com/auth/callback"],
      "contact_email": "dev@yourcompany.com",
      "application_type": "web|spa|mobile|desktop",
      "logo_url": "https://yourapp.com/logo.png"
    }
  3. Receive Credentials After approval, you'll receive:

    • Client ID: Public identifier for your application
    • Client Secret: Confidential key (only for confidential clients)
    • Application Status: Active/Pending/Suspended

Application Types ​

Confidential Clients ​

Server-side applications that can securely store credentials:

Characteristics:

  • Can store client secret securely
  • Server-side token exchange
  • Supports refresh tokens
  • Examples: Traditional web apps, backend services

Configuration:

javascript
{
  "application_type": "web",
  "token_endpoint_auth_method": "client_secret_post",
  "grant_types": ["authorization_code", "refresh_token"],
  "require_pkce": false // Optional but recommended
}

Public Clients ​

Applications that cannot securely store credentials:

Characteristics:

  • Cannot store client secret
  • Must use PKCE for security
  • Client-side token handling
  • Examples: SPAs, mobile apps, desktop apps

Configuration:

javascript
{
  "application_type": "spa", // or "mobile", "desktop"
  "token_endpoint_auth_method": "none",
  "grant_types": ["authorization_code", "refresh_token"],
  "require_pkce": true // Mandatory
}

Application Configuration ​

Redirect URI Management ​

Redirect URIs are critical for security. They must be:

  • Exact match: No wildcards or partial matches
  • HTTPS only: Exception for localhost during development
  • Pre-registered: All URIs must be registered in advance

Valid Redirect URIs ​

✅ https://yourapp.com/callback
✅ https://app.yourcompany.com/auth/callback
✅ http://localhost:3000/callback (development only)
✅ https://yourapp.com/oauth/wetrials/callback

Invalid Redirect URIs ​

❌ http://yourapp.com/callback (not HTTPS)
❌ https://yourapp.com/* (wildcards not allowed)
❌ https://*.yourapp.com/callback (subdomains must be explicit)
❌ https://yourapp.com (must be complete path)

Development vs Production ​

Development Configuration ​

For local development:

javascript
// Development OAuth config
const devConfig = {
  clientId: 'dev_client_id',
  redirectUri: 'http://localhost:3000/callback',
  authEndpoint: 'https://sandbox.auth.wetrials.com/v1/oauth/authorize',
  tokenEndpoint: 'https://sandbox.auth.wetrials.com/v1/oauth/token',
};

Production Configuration ​

For production deployment:

javascript
// Production OAuth config
const prodConfig = {
  clientId: 'prod_client_id',
  redirectUri: 'https://app.yourcompany.com/callback',
  authEndpoint: 'https://auth.wetrials.com/v1/oauth/authorize',
  tokenEndpoint: 'https://auth.wetrials.com/v1/oauth/token',
};

Environment-Specific Applications ​

We recommend registering separate applications for each environment:

EnvironmentPurposeRedirect URI Example
DevelopmentLocal testinghttp://localhost:3000/callback
StagingPre-production testinghttps://staging.yourapp.com/callback
ProductionLive applicationhttps://yourapp.com/callback

Application Management ​

Viewing Application Details ​

Application details can be viewed through the WeTrials Developer Dashboard (coming soon) or by contacting support.

Application Information Includes:

  • Client ID and name
  • Registration date
  • Redirect URIs
  • Granted scopes
  • Usage statistics
  • Status and health

Updating Application Settings ​

To update your application settings:

  1. Contact Support with requested changes
  2. Provide verification (client ID and registered email)
  3. Specify changes (new redirect URIs, updated description, etc.)

Updatable Fields:

  • Application name and description
  • Redirect URIs (add/remove)
  • Contact email
  • Logo URL
  • Website URL

Non-Updatable Fields:

  • Client ID
  • Client Secret (can only be rotated)
  • Application type

Rotating Client Secrets ​

For security, rotate client secrets periodically:

bash
# Request secret rotation
POST /api/v1/oauth/applications/{client_id}/rotate-secret
Authorization: Bearer {management_token}

# Response
{
  "client_id": "your_client_id",
  "new_client_secret": "new_secret_value",
  "secret_expires_at": "2024-12-31T23:59:59Z",
  "old_secret_valid_until": "2024-01-31T23:59:59Z"
}

Secret Rotation Process:

  1. Request new secret
  2. Update application configuration
  3. Deploy with new secret
  4. Verify functionality
  5. Old secret remains valid for grace period (30 days)

Application Lifecycle ​

Application States ​

StateDescriptionAPI AccessUser Auth
pendingAwaiting approval❌❌
activeFully functional✅✅
suspendedTemporarily disabled❌❌
deprecatedBeing phased out⚠️ Limited✅
revokedPermanently disabled❌❌

Activation Process ​

New applications go through activation:

  1. Submit Registration → Status: pending
  2. Review by WeTrials → Verification and approval
  3. Activation → Status: active
  4. Notification → Email with credentials

Suspension and Revocation ​

Applications may be suspended for:

  • Violation of terms of service
  • Suspicious activity or abuse
  • Security concerns
  • Excessive API usage

Suspension Process:

  1. Warning notification (if not critical)
  2. Application suspended
  3. Investigation period
  4. Resolution: Reactivation or revocation

Monitoring and Analytics ​

Usage Metrics ​

Track your application's OAuth usage:

javascript
// Fetch application metrics
GET /api/v1/oauth/applications/{client_id}/metrics
Authorization: Bearer {management_token}

// Response
{
  "client_id": "your_client_id",
  "period": "last_30_days",
  "metrics": {
    "total_authorizations": 1523,
    "unique_users": 487,
    "token_exchanges": 1498,
    "token_refreshes": 3847,
    "failed_attempts": 25,
    "average_session_duration": "4h 23m"
  },
  "top_scopes": [
    { "scope": "read:profile", "usage": 1523 },
    { "scope": "read:studies", "usage": 1245 },
    { "scope": "write:studies", "usage": 432 }
  ]
}

Audit Logs ​

Access detailed audit logs for security and compliance:

javascript
// Fetch audit logs
GET /api/v1/oauth/applications/{client_id}/audit-logs
Authorization: Bearer {management_token}

// Response
{
  "logs": [
    {
      "timestamp": "2024-01-15T10:23:45Z",
      "event": "authorization_granted",
      "user_id": "user_123",
      "scopes": ["read:profile", "read:studies"],
      "ip_address": "192.168.1.1",
      "user_agent": "Mozilla/5.0..."
    },
    {
      "timestamp": "2024-01-15T10:24:12Z",
      "event": "token_exchanged",
      "user_id": "user_123",
      "success": true
    }
  ]
}

Rate Limit Monitoring ​

Monitor your application's rate limit usage:

javascript
// Check rate limit status
GET /api/v1/oauth/applications/{client_id}/rate-limits
Authorization: Bearer {management_token}

// Response
{
  "client_id": "your_client_id",
  "limits": {
    "authorization": {
      "limit": 1000,
      "remaining": 945,
      "reset_at": "2024-01-15T11:00:00Z"
    },
    "token_exchange": {
      "limit": 5000,
      "remaining": 4832,
      "reset_at": "2024-01-15T11:00:00Z"
    },
    "api_calls": {
      "limit": 100000,
      "remaining": 87234,
      "reset_at": "2024-01-15T11:00:00Z"
    }
  }
}

Security Best Practices ​

Secure Storage ​

Client Secrets ​

javascript
// ❌ WRONG - Never hardcode secrets
const clientSecret = 'abc123_secret_key';

// ✅ CORRECT - Use environment variables
const clientSecret = process.env.WETRIALS_CLIENT_SECRET;

// ✅ BETTER - Use secret management service
const clientSecret = await secretManager.getSecret('wetrials-client-secret');

Redirect URI Validation ​

javascript
// Validate redirect URI on your server
function validateRedirectUri(uri) {
  const allowedUris = ['https://yourapp.com/callback', 'https://yourapp.com/auth/callback'];

  if (!allowedUris.includes(uri)) {
    throw new Error('Invalid redirect URI');
  }

  return uri;
}

Application Security Checklist ​

  • [ ] Store client secret securely (environment variables or secret manager)
  • [ ] Use HTTPS for all redirect URIs (except localhost)
  • [ ] Implement PKCE for public clients
  • [ ] Rotate client secrets periodically
  • [ ] Monitor for suspicious activity
  • [ ] Implement rate limiting on your side
  • [ ] Log all OAuth events for audit
  • [ ] Validate all redirect URIs
  • [ ] Use separate apps for different environments
  • [ ] Implement proper error handling

Troubleshooting ​

Common Issues ​

Invalid Client Error ​

json
{
  "error": "invalid_client",
  "error_description": "Client authentication failed"
}

Solution: Verify client ID and secret are correct and application is active.

Redirect URI Mismatch ​

json
{
  "error": "invalid_request",
  "error_description": "Redirect URI mismatch"
}

Solution: Ensure redirect URI exactly matches registered URI.

Application Suspended ​

json
{
  "error": "unauthorized_client",
  "error_description": "Application is suspended"
}

Solution: Contact support to resolve suspension reason.

Testing Your Application ​

Test Authorization Flow ​

bash
# Test authorization endpoint
curl -I "https://auth.wetrials.com/v1/oauth/authorize?\
client_id=YOUR_CLIENT_ID&\
response_type=code&\
redirect_uri=https://yourapp.com/callback&\
scope=read:profile"

Test Token Exchange ​

bash
# Test token endpoint
curl -X POST "https://auth.wetrials.com/v1/oauth/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code&\
code=AUTH_CODE&\
client_id=YOUR_CLIENT_ID&\
client_secret=YOUR_CLIENT_SECRET&\
redirect_uri=https://yourapp.com/callback"

Migration Guide ​

Migrating from API Keys ​

If you're migrating from API key authentication to OAuth:

  1. Register OAuth Application
  2. Implement OAuth flow alongside existing API key auth
  3. Migrate users gradually
  4. Monitor both authentication methods
  5. Deprecate API keys after full migration
javascript
// Support both authentication methods during migration
async function authenticate(request) {
  // Check for OAuth token first
  const authHeader = request.headers.authorization;
  if (authHeader?.startsWith('Bearer ')) {
    return validateOAuthToken(authHeader.substring(7));
  }

  // Fall back to API key (deprecated)
  const apiKey = request.headers['x-api-key'];
  if (apiKey) {
    console.warn('API key authentication is deprecated');
    return validateApiKey(apiKey);
  }

  throw new Error('No authentication provided');
}

Support and Resources ​

Getting Help ​

Reporting Issues ​

When reporting issues, include:

  • Client ID (never include client secret)
  • Error messages and codes
  • Request/response examples (sanitized)
  • Timestamp of occurrence
  • Steps to reproduce

Next Steps ​