Custom Security Schemes
Custom Security Schemes define a JSON Schema for SDK security options. Combined with SDK Hooks, custom authentication and authorization schemes can be implemented beyond OpenAPI’s capabilities.
Availability
Custom Security Schemes are only available for Business and Enterprise users.
Language support
TypeScript | Python | Go | C# | Java | PHP | Swift | Ruby |
---|---|---|---|---|---|---|---|
✅ | ✅ | ✅ | 🏗️ | 🏗️ | 🏗️ | 🏗️ | 🏗️ |
Define a custom security scheme
Define the custom security scheme under components -> securitySchemes
and reference it in the security
section. Set the type
to http
and the scheme
to custom
. Use the x-speakeasy-custom-security-scheme
extension to specify a JSON Schema. This schema must include at least one property and can accommodate multiple properties with different schema definitions.
openapi: 3.1.0info:title: Custom Security Scheme Exampleversion: 1.0.0security:- myCustomScheme: [] # reference to the custom security scheme defined below# ...components:securitySchemes:myCustomScheme: # defined as usual under components -> securitySchemestype: httpscheme: custom # type: http, scheme: custom is used to identify the custom security schemex-speakeasy-custom-security-scheme: # A JSON Schema is then provided via the x-speakeasy-custom-security-scheme extensionschema:type: object # the JSON Schema MUST be defined as an object with at least one property, but can then have any number of properties with any schemaproperties:appId:type: stringexample: app-speakeasy-123secret:type: stringexample: MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIrequired:- appId- secret
Initialize the custom security scheme
Once the SDK is regenerated, the custom security scheme can be configured globally or per operation, depending on the security
definitions.
import { SDK } from "openapi";const sdk = new SDK({security: {appId: "app-speakeasy-123",secret: "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI",},});
Use the custom security scheme
Use SDK Hooks to access user-provided security values and enable custom authentication workflows, like adding headers to requests.
The following example illustrates accessing a custom security scheme in a hook and adding headers to a request:
import { Security$outboundSchema } from "../models/components/security.js";import { BeforeRequestContext, BeforeRequestHook } from "./types.js";export class CustomSecurityHook implements BeforeRequestHook {beforeRequest(hookCtx: BeforeRequestContext, request: Request): Request {let sec = hookCtx.securitySource;if (typeof sec === "function") {sec = sec();}if (!sec) {throw new Error("security source is not defined");}// Use the Zod schema to parse the security objectconst customSec = Security$outboundSchema.parse(sec);// Access the values from the parsed object and add them to the request headersrequest.headers.set("X-Security-App-Id", customSec.appId);request.headers.set("X-Security-Secret", customSec.secret);return request;}}