Skip to main content

Token Utilities

The MentraOS SDK provides utility functions for creating and validating JWT tokens used for App authentication. These utilities are primarily used for implementing secure authentication mechanisms, especially for webviews.

TokenUtils Namespace

createToken()

Creates a signed JWT token for App authentication.
Parameters:
  • payload: The data to include in the token payload (excluding auto-generated fields)
  • config: Configuration containing the secret key and optional expiration
Returns: The signed JWT token string Example:

validateToken()

Validates a JWT token using the provided secret key.
Parameters:
  • token: The JWT token string to validate
  • secretKey: The secret key used to sign the token
Returns: A TokenValidationResult object with validation status and either the payload or error message Example:

generateWebviewUrl()

Appends a JWT token as a query parameter to a base URL, making it easy to create authenticated webview URLs.
Parameters:
  • baseUrl: The base URL for the webview
  • token: The JWT token string
Returns: The full URL including the token parameter Example:

extractTokenFromUrl()

Extracts the JWT token from the ‘token’ query parameter of a URL.
Parameters:
  • url: The URL string potentially containing the token
Returns: The extracted token string, or null if not found or the URL is invalid Example:

AppTokenPayload

The data structure embedded within a App JWT token.

TokenValidationResult

The result returned by the validateToken utility function.

TokenConfig

Configuration options for creating a App token using createToken.

Token Usage in AppServer

The AppServer class includes a protected method for generating tokens:
This method is available when you extend the AppServer class and is useful for generating tokens within webhook handlers.

Common Token Usage Patterns

Creating a Secure Webview

Validating Tokens in a Web Application

Security Considerations

  1. Secret Key Management: Never expose your App secret key in client-side code. Always keep it on your server.
  2. Token Expiration: Set appropriate expiration times for tokens based on your security requirements.
  3. HTTPS: Always use HTTPS for webviews to prevent token interception.
  4. Validation: Always validate tokens on your server before granting access to protected resources.
  5. Payload Size: Keep token payloads minimal to reduce overhead and improve performance.