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 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 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 Custom Security Scheme

SDK Hooks provde access to user-provided security values, enabling custom authentication workflows such as adding headers to requests.

Example of accessing the 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;
}
}