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.

Info Icon

Availability

Custom Security Schemes are only available for Business and Enterprise users.

Language support

TypeScriptPythonGoC#JavaPHPSwiftRuby
🏗️🏗️🏗️🏗️🏗️

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.0
info:
title: Custom Security Scheme Example
version: 1.0.0
security:
- myCustomScheme: [] # reference to the custom security scheme defined below
# ...
components:
securitySchemes:
myCustomScheme: # defined as usual under components -> securitySchemes
type: http
scheme: custom # type: http, scheme: custom is used to identify the custom security scheme
x-speakeasy-custom-security-scheme: # A JSON Schema is then provided via the x-speakeasy-custom-security-scheme extension
schema:
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 schema
properties:
appId:
type: string
example: app-speakeasy-123
secret:
type: string
example: MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI
required:
- 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 object
const customSec = Security$outboundSchema.parse(sec);
// Access the values from the parsed object and add them to the request headers
request.headers.set("X-Security-App-Id", customSec.appId);
request.headers.set("X-Security-Secret", customSec.secret);
return request;
}
}