Dynamic authentication
Your API may require dynamic authentication where credentials need to be generated or refreshed for each request, such as signing short-lived JWTs or rotating tokens. Fern-generated SDKs support this pattern through language-specific approaches.
Language-specific guides
Each language has its own recommended approach for implementing dynamic authentication:
Use custom fetcher middleware to inject authentication logic in a single place for all requests. Supports JWT signing, OAuth token refresh, and more.
Use method overrides to inject authentication logic for each API call. Supports JWT signing, OAuth token refresh, and more.
Common use cases
Dynamic authentication is useful for several scenarios:
- Short-lived JWT signing: Generate and sign JWTs that expire after a short period (e.g., 15 seconds) for enhanced security
- OAuth token refresh: Automatically refresh expired access tokens before each request
- HMAC (Hash-based Message Authentication Code) signing: Sign requests with HMAC signatures based on request content
- Rotating API keys: Switch between multiple API keys based on rate limits or other criteria
- Time-based tokens: Generate tokens that include timestamps or nonces for replay protection
Important considerations
When implementing dynamic authentication, keep these language-agnostic considerations in mind:
Security
- Secure key storage: Never hardcode private keys or secrets; use environment variables or secure key management systems
- Server-side only: For JWT signing with private keys, ensure this is only done in server-side code, never in browser environments
- Avoid double authentication: If your API already uses bearer token authentication in the Fern definition, be careful not to override existing authentication headers
Performance
- Token caching: Cache tokens to avoid regenerating them on every request, balancing security (shorter token lifetime) with performance (less frequent regeneration)
- Grace period: Refresh tokens slightly before they expire to avoid edge cases where a token expires during request processing
- Concurrency: Be mindful of race conditions when caching tokens in multi-threaded environments
Time synchronization
- Clock drift: Be aware of potential clock drift between your client and server; consider adding tolerance to token expiration checks
- Timestamp precision: Use Unix timestamps (seconds since epoch) for JWT
iatandexpclaims to match standards
See also
- Adding custom code - Learn more about extending generated SDKs
- TypeScript custom code - TypeScript-specific customization guide
- Python custom code - Python-specific customization guide