Adding Authentication
Defining Authenticators
import {
Authenticator,
AuthenticationController,
OperationRequestContext,
HTTPBearerAuthenticationCredentials,
} from "@simply-openapi/controllers";
import { Unauthorized } from "http-errors";
@Authenticator("myAuth", {
type: "http",
scheme: "bearer",
})
class MyAuthenticator implements AuthenticationController {
async authenticate(
value: HTTPBearerAuthenticationCredentials,
scopes: string[],
ctx: OperationRequestContext,
) {
const user = await decodeBearerToken(value);
if (!user) {
// Returning false is the equivalent of throwing
// an Unauthorized http-error with the default message.
return false;
}
// It is your responsibility to check the scopes
// in the authentication request.
if (!scopes.every((cope) => user.scopes.includes(scope))) {
// Thrown errors will be recorded.
// If all authentication options reject the request,
// the last thrown http-error will be used.
throw new Unauthorized("Insufficient permissions");
}
// If authentication succeeds, you can return a value that will
// be passed to handler method arguments decorated to recieve
// the authenticated user.
// Any non-falsy value will be interpreted as a successful auth.
return user;
}
}
// When creating the spec, pass the authenticator to the list of controllers.
const openApiSpec = createOpenAPIFromControllers(
{ title: "My App", version: "1.0.0" },
[MyAuthenticator, ...controllers],
);HTTP Basic authentication
HTTP Bearer authentication
Requiring Authentication
Requiring authentication for all endpoints
Requiring authentication on all methods of a controller
Requiring authentication on a specific method
Retrieving the authentication result
Last updated