Pre-release — content may change.

Widgets

Authentication

Understanding widget tokens and secure access for organization widgets

Widget authentication uses two distinct approaches depending on which resources the widget manages. This guide explains when and how to use each authentication method.

Authentication Methods

Regular API Tokens

Used for: Person-focused widgets

Person widgets like createPersonProfile and editPersonPreferences use standard JWT API tokens that authenticate as a specific user:

Wicket.widgets.createPersonProfile({
  accessToken: userJwtToken, // Standard JWT token
  personId: personUuid,
  rootEl: container
});

These tokens:

  • Are generated using your API secret and user UUID
  • Grant access based on the authenticated user's permissions
  • Follow standard JWT authentication patterns
  • See the Authentication Guide for details

Widget Tokens

Used for: Organization-focused widgets

Organization widgets like editOrganizationProfile and editAdditionalInfo (for organizations) require special widget tokens obtained via the API:

Wicket.widgets.editOrganizationProfile({
  accessToken: widgetToken, // Widget token, not regular JWT
  orgId: orgUuid,
  rootEl: container
});

These tokens:

  • Are created via the /widget_tokens API endpoint
  • Grant temporary access to modify organization details
  • Work regardless of the user's roles in the system
  • Require server-side generation with permission checks

Why Widget Tokens?

Widget tokens exist to shift permission control from Wicket to your application.

The Problem

Organization management requires nuanced permissions that vary by use case:

  • A member portal might allow any organization contact to edit company details
  • An enterprise system might require specific approval workflows
  • A CMS integration might have its own role hierarchy

Wicket's built-in role system can't accommodate every custom permission model.

The Solution

Widget tokens let your application decide who can edit organizations:

// Your server-side code controls permissions
app.post('/api/widget-token', async (req, res) => {
  const { userId, orgId } = req.body;

  // YOUR custom permission logic
  if (!userCanEditOrganization(userId, orgId)) {
    return res.status(403).json({ error: 'Forbidden' });
  }

  // Only issue token if your checks pass
  const widgetToken = await createWidgetToken(userId, orgId);
  res.json({ token: widgetToken });
});

This approach:

  • ✅ Gives you complete control over permissions
  • ✅ Lets you implement custom business logic
  • ✅ Works with your existing authorization system
  • ✅ Provides temporary, scoped access

Creating Widget Tokens

API Endpoint

POST /widget_tokens
Content-Type: application/vnd.api+json
Authorization: Bearer YOUR_ADMIN_JWT_TOKEN

Request Body

{
  "data": {
    "type": "widget_tokens",
    "attributes": {
      "widget_context": "organizations"
    },
    "relationships": {
      "subject": {
        "data": {
          "type": "people",
          "id": "person-uuid"
        }
      },
      "resource": {
        "data": {
          "type": "organizations",
          "id": "org-uuid"
        }
      }
    }
  }
}

Parameters:

FieldDescription
widget_contextMust be "organizations" for organization widgets
subjectThe person who will use the widget (person UUID)
resourceThe organization being modified (org UUID)

Response

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

The response contains a simple JSON object with the widget token to use with the JavaScript widget.

Important: Widget tokens are returned only once. Store them temporarily for immediate use, but don't persist them long-term.

Implementation Examples

Node.js / Express

const express = require('express');
const fetch = require('node-fetch');

const app = express();
app.use(express.json());

// Endpoint to generate widget tokens
app.post('/api/widget-token', async (req, res) => {
  const { personId, orgId } = req.body;

  try {
    // Create widget token via Wicket MDP API
    const response = await fetch(
      `${process.env.WICKET_API_URL}/widget_tokens`,
      {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${process.env.WICKET_ADMIN_TOKEN}`,
          'Content-Type': 'application/vnd.api+json'
        },
        body: JSON.stringify({
          data: {
            type: 'widget_tokens',
            attributes: {
              widget_context: 'organizations'
            },
            relationships: {
              subject: {
                data: {
                  type: 'people',
                  id: personId
                }
              },
              resource: {
                data: {
                  type: 'organizations',
                  id: orgId
                }
              }
            }
          }
        })
      }
    );

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.errors?.[0]?.detail || 'Failed to create token');
    }

    // Return widget token to client
    res.json({
      widgetToken: data.token
    });
  } catch (error) {
    console.error('Error creating widget token:', error);
    res.status(500).json({ error: error.message });
  }
});
app.post('/api/widget-token', async (req, res) => {
  const { personId, orgId } = req.body;
  const currentUser = req.user; // From your auth middleware

  // 1. Verify user is authenticated
  if (!currentUser) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  // 2. Check if user can edit this organization
  const canEdit = await checkOrganizationPermission(currentUser.id, orgId);
  if (!canEdit) {
    return res.status(403).json({ error: 'You do not have permission to edit this organization' });
  }

  // 3. Generate widget token
  try {
    const response = await fetch(
      `${process.env.WICKET_API_URL}/widget_tokens`,
      {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${process.env.WICKET_ADMIN_TOKEN}`,
          'Content-Type': 'application/vnd.api+json'
        },
        body: JSON.stringify({
          data: {
            type: 'widget_tokens',
            attributes: { widget_context: 'organizations' },
            relationships: {
              subject: { data: { type: 'people', id: personId } },
              resource: { data: { type: 'organizations', id: orgId } }
            }
          }
        })
      }
    );

    const data = await response.json();
    res.json({ widgetToken: data.token });
  } catch (error) {
    console.error('Widget token error:', error);
    res.status(500).json({ error: 'Failed to create widget token' });
  }
});

// Example permission check function
async function checkOrganizationPermission(userId, orgId) {
  // Your custom logic here:
  // - Check if user is an org admin
  // - Verify user is part of the organization
  // - Check custom role permissions
  // - Query your database
  // etc.

  const userOrgs = await getUserOrganizations(userId);
  return userOrgs.some(org => org.id === orgId && org.canEdit);
}
app.post('/api/widget-token', async (req, res) => {
  const { personId, orgId } = req.body;

  // Validate request
  if (!personId || !orgId) {
    return res.status(400).json({
      error: 'Missing required parameters: personId and orgId'
    });
  }

  // Permission check
  try {
    const hasPermission = await userCanEditOrg(req.user.id, orgId);
    if (!hasPermission) {
      return res.status(403).json({
        error: 'Permission denied',
        detail: 'You do not have access to edit this organization'
      });
    }
  } catch (error) {
    console.error('Permission check failed:', error);
    return res.status(500).json({
      error: 'Permission check failed'
    });
  }

  // Create widget token
  try {
    const response = await fetch(
      `${process.env.WICKET_API_URL}/widget_tokens`,
      {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${process.env.WICKET_ADMIN_TOKEN}`,
          'Content-Type': 'application/vnd.api+json'
        },
        body: JSON.stringify({
          data: {
            type: 'widget_tokens',
            attributes: { widget_context: 'organizations' },
            relationships: {
              subject: { data: { type: 'people', id: personId } },
              resource: { data: { type: 'organizations', id: orgId } }
            }
          }
        })
      }
    );

    if (!response.ok) {
      const errorData = await response.json();
      console.error('Wicket MDP API error:', errorData);

      if (response.status === 404) {
        return res.status(404).json({
          error: 'Resource not found',
          detail: 'Person or organization does not exist'
        });
      }

      if (response.status === 401 || response.status === 403) {
        return res.status(500).json({
          error: 'API authentication failed',
          detail: 'Server configuration error'
        });
      }

      throw new Error('Failed to create widget token');
    }

    const data = await response.json();

    res.json({
      widgetToken: data.token,
      expiresIn: 3600 // Example: token expires in 1 hour
    });

  } catch (error) {
    console.error('Widget token creation failed:', error);
    res.status(500).json({
      error: 'Internal server error',
      detail: 'Failed to create widget token'
    });
  }
});

PHP

<?php
use Wicket\Client;

// Get request data
$data = json_decode(file_get_contents('php://input'), true);
$personId = $data['personId'] ?? null;
$orgId = $data['orgId'] ?? null;

if (!$personId || !$orgId) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing personId or orgId']);
    exit;
}

// Optional: Add your permission check here
// if (!userCanEditOrganization($currentUserId, $orgId)) {
//     http_response_code(403);
//     echo json_encode(['error' => 'Forbidden']);
//     exit;
// }

try {
    // Initialize Wicket SDK
    $client = new Client(
        getenv('WICKET_API_KEY'),
        getenv('WICKET_JWT_SECRET'),
        'https://your-tenant-api.wicketcloud.com'
    );

    // Authorize as admin user
    $client->authorize(getenv('WICKET_ADMIN_PERSON_ID'));

    // Create widget token
    $response = $client->post('widget_tokens', [
        'data' => [
            'type' => 'widget_tokens',
            'attributes' => [
                'widget_context' => 'organizations'
            ],
            'relationships' => [
                'subject' => [
                    'data' => [
                        'type' => 'people',
                        'id' => $personId
                    ]
                ],
                'resource' => [
                    'data' => [
                        'type' => 'organizations',
                        'id' => $orgId
                    ]
                ]
            ]
        ]
    ]);

    // Return widget token to client
    header('Content-Type: application/json');
    echo json_encode([
        'widgetToken' => $response['token']
    ]);

} catch (Exception $e) {
    error_log('Error creating widget token: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Failed to create widget token']);
}
?>

See the Wicket PHP SDK for more details.

Ruby / Rails

class WidgetTokensController < ApplicationController
  before_action :authenticate_user!

  def create
    person_id = params[:personId]
    org_id = params[:orgId]

    # Permission check
    unless current_user.can_edit_organization?(org_id)
      render json: { error: 'Forbidden' }, status: :forbidden
      return
    end

    # Create widget token
    response = HTTParty.post(
      "#{ENV['WICKET_API_URL']}/widget_tokens",
      headers: {
        'Authorization' => "Bearer #{ENV['WICKET_ADMIN_TOKEN']}",
        'Content-Type' => 'application/vnd.api+json'
      },
      body: {
        data: {
          type: 'widget_tokens',
          attributes: {
            widget_context: 'organizations'
          },
          relationships: {
            subject: {
              data: {
                type: 'people',
                id: person_id
              }
            },
            resource: {
              data: {
                type: 'organizations',
                id: org_id
              }
            }
          }
        }
      }.to_json
    )

    if response.success?
      token = response['token']
      render json: { widgetToken: token }
    else
      render json: { error: 'Failed to create token' }, status: :internal_server_error
    end
  end
end

Client-Side Usage

Fetching Token from Your Server

// Client-side code
async function loadOrganizationWidget(personId, orgId) {
  try {
    // 1. Request widget token from your server
    const response = await fetch('/api/widget-token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        personId: personId,
        orgId: orgId
      })
    });

    if (!response.ok) {
      throw new Error('Failed to get widget token');
    }

    const data = await response.json();

    // 2. Use token with widget
    return Wicket.widgets.editOrganizationProfile({
      accessToken: data.widgetToken,
      orgId: orgId,
      apiRoot: 'https://your-org-api.wicketcloud.com',
      rootEl: document.getElementById('org-editor'),
      lang: 'en'
    });

  } catch (error) {
    console.error('Error loading widget:', error);
    throw error;
  }
}

// Usage
Wicket.ready(function() {
  loadOrganizationWidget('person-uuid', 'org-uuid')
    .then(function(widget) {
      console.log('Organization widget loaded');

      widget.listen(widget.eventTypes.SAVE_SUCCESS, function() {
        alert('Organization profile updated!');
      });
    })
    .catch(function(error) {
      alert('Unable to load organization editor: ' + error.message);
    });
});

Security Best Practices

1. Never Expose API Secrets Client-Side

// ❌ DANGEROUS: Never do this
const token = jwt.sign(
  { user_uuid: personId },
  'YOUR_API_SECRET', // ⚠️ Exposed in client code!
  { algorithm: 'HS256' }
);

// ✅ CORRECT: Generate tokens server-side
app.post('/api/widget-token', async (req, res) => {
  const token = await createWidgetToken(req.body.personId, req.body.orgId);
  res.json({ token });
});

2. Always Validate Permissions

Don't trust client requests—verify permissions server-side:

app.post('/api/widget-token', async (req, res) => {
  const { personId, orgId } = req.body;
  const currentUser = req.user;

  // ✅ REQUIRED: Verify current user has permission
  const hasAccess = await db.query(
    'SELECT 1 FROM org_members WHERE person_id = ? AND org_id = ? AND can_edit = true',
    [currentUser.id, orgId]
  );

  if (!hasAccess) {
    return res.status(403).json({ error: 'Forbidden' });
  }

  // Only create token if permission check passes
  const token = await createWidgetToken(personId, orgId);
  res.json({ widgetToken: token });
});

3. Use HTTPS

Always serve widget tokens over HTTPS:

// ✅ GOOD: HTTPS endpoint
https://your-site.com/api/widget-token

// ❌ DANGEROUS: HTTP exposes tokens
http://your-site.com/api/widget-token

4. Implement Rate Limiting

Prevent abuse by rate limiting token generation:

const rateLimit = require('express-rate-limit');

const widgetTokenLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 10, // 10 requests per window
  message: 'Too many token requests, please try again later'
});

app.post('/api/widget-token', widgetTokenLimiter, async (req, res) => {
  // Token generation logic
});

5. Log Token Creation

Track token generation for security auditing:

app.post('/api/widget-token', async (req, res) => {
  const { personId, orgId } = req.body;

  // Log token request
  await auditLog.create({
    action: 'widget_token_created',
    userId: req.user.id,
    subjectId: personId,
    resourceId: orgId,
    timestamp: new Date(),
    ipAddress: req.ip
  });

  // Create token...
});

6. Handle Token Expiration

Widget tokens may expire. Handle expiration gracefully:

widget.listen(widget.eventTypes.ERROR, function(error) {
  if (error.code === 'INVALID_TOKEN' || error.code === 'TOKEN_EXPIRED') {
    // Token expired, request new one
    refreshWidgetToken()
      .then(newToken => {
        // Reload widget with new token
        widget.clear();
        loadWidget(newToken);
      });
  }
});

Common Permission Patterns

Pattern 1: Organization Membership

Allow any organization member to edit:

async function userCanEditOrg(userId, orgId) {
  const membership = await db.query(
    'SELECT 1 FROM connections WHERE person_id = ? AND organization_id = ?',
    [userId, orgId]
  );
  return membership.length > 0;
}

Pattern 2: Role-Based Access

Require specific roles:

async function userCanEditOrg(userId, orgId) {
  const admin = await db.query(
    'SELECT 1 FROM org_roles WHERE person_id = ? AND org_id = ? AND role IN (?, ?)',
    [userId, orgId, 'admin', 'org_editor']
  );
  return admin.length > 0;
}

Pattern 3: Approval Workflow

Require approval before granting access:

async function userCanEditOrg(userId, orgId) {
  const approval = await db.query(
    'SELECT approved FROM edit_requests WHERE user_id = ? AND org_id = ? AND approved = true',
    [userId, orgId]
  );
  return approval.length > 0;
}

Pattern 4: Time-Limited Access

Grant temporary access:

async function userCanEditOrg(userId, orgId) {
  const accessGrant = await db.query(
    'SELECT expires_at FROM temp_access WHERE user_id = ? AND org_id = ?',
    [userId, orgId]
  );

  if (accessGrant.length === 0) return false;

  return new Date(accessGrant[0].expires_at) > new Date();
}

Troubleshooting

Token Creation Fails

Problem: /widget_tokens returns 401 or 403

Solutions:

  • Verify WICKET_ADMIN_TOKEN is valid and has proper permissions
  • Check that the admin token hasn't expired
  • Ensure you're using an admin-level JWT token, not a regular user token

Widget Shows "Invalid Token" Error

Problem: Widget displays authentication error

Solutions:

  • Verify the token from /widget_tokens response is being used correctly
  • Check that you're passing the token as accessToken parameter
  • Ensure the token hasn't expired (if applicable)
  • Verify person and organization UUIDs are correct

Permission Denied Error

Problem: Server returns 403 when requesting token

Solutions:

  • Check your permission logic on the server side
  • Verify the current user actually has access to the organization
  • Review audit logs to see why permission check failed

On this page