Skip to main content

Authentication

SDKs generated by liblab support a range of authentication methods to access your APIs. This guide shows how to configure your SDK generation depending on the authentication method you use.

You can have multiple values if your API supports multiple authentication types, as long as they don't conflict with each other. For example, both Basic authentication and Bearer token authentication both use the Authentication header in your API, so you can't have both of these set at the same time.

The different authentication types are set in the config file. When your SDK is generated the relevant configuration for the authentication type selected is added to the SDK. In the case of C# and Go, a custom config object is also generated that contains this configuration, with each authentication method creating a different config depending on the parameters required.

liblab also supports refresh tokens for authentication.

Authentication types

Authentication typeConfig file valueDescription
API keyapikeyAPI key authentication
Basic authenticationbasicBasic authentication with a user name and password
Bearer tokenbearerBearer token authentication
Custom access tokencustomCustom access token authentication
OAuthoauthOAuth authentication

You can also leverage hooks to add custom authentication to your SDK, or to modify the authentication process.

API Key

If your API needs an API key, this can be sent in a header with every request. To configure API key authentication, set the following in your config file:

liblab.config.json
{
"auth": [
"apikey"
]
}

By default the X-API-KEY header is used to send the API key, but this can be configured using the config file, or set in code when using the SDK:

liblab.config.json
{
...
"customizations": {
"authentication": {
"apiKey": {
"header": "MY_CUSTOM_APIKEY_HEADER"
}
}
}
...
}

The API key can be set either when you initialize the SDK, or later.

To set the API key when you initialize the SDK, use the following code:

The API key is set in the SdkConfig object that is passed to the SDK constructor.

src/index.ts
export interface SdkConfig {
apiKey?: string;
...
}

export class ExcitingSoda {
constructor(config: SdkConfig)
...
}
src/example.ts
import { ExcitingSoda } from 'exciting-soda';

const sdk = new ExcitingSoda({ apiKey: process.env.EXCITINGSODA_API_KEY });

To set the API key later, use the following code:

To set the API key, use the setApiKey method on the ExcitingSoda class.

src/index.ts
export class ExcitingSoda {
setApiKey(apiKey: string): void {}
...
}
src/example.ts
import { ExcitingSoda } from 'exciting-soda';

const sdk = new ExcitingSoda();
sdk.setApiKey('MY_API_KEY');

If your API requires the API key as a query parameter instead of in a header, you can configure this using hooks as described in Customize your SDK with hooks tutorial.

Basic authentication

If your API uses basic authentication, the user name and password can be sent as a base64 encoded string in the Authorization header with every request. To configure basic authentication, set the following in your config file:

liblab.config.json
{
"auth": [
"basic"
]
}

This will send the provided user name and password encoded in base64 in the Authorization header:

"Authorization": "Basic bWFkZSB5b3UgbG9vaw=="

The user name and password can be set either when you initialize the SDK, or later.

To set the user name and password when you initialize the SDK, use the following code:

The user name and password is set in the SdkConfig object that is passed to the SDK constructor.

src/index.ts
export interface SdkConfig {
username?: string;
password?: string;
...
}

export class ExcitingSoda {
constructor(config: SdkConfig)
...
}
src/example.ts
import { ExcitingSoda } from 'exciting-soda';

const sdk = new ExcitingSoda({
username: process.env.EXCITINGSODA_USERNAME,
password: process.env.EXCITINGSODA_PASSWORD
});

To set the user name and password later, use the following code:

To set the user name and password, use the setUsername and setPassword methods on the ExcitingSoda class.

src/index.ts
export class ExcitingSoda {
setUsername(username: string): void {
}

setPassword(password: string): void {
}
}
src/example.ts
import { ExcitingSoda } from 'exciting-soda';

const sdk = new ExcitingSoda();
sdk.setUsername('MY_USERNAME');
sdk.setPassword('MY_PASSWORD');

Bearer token

If your API uses a bearer token, this can be sent in the Authorization header with every request. To configure bearer token authentication, set the following in your config file:

liblab.config.json
{
"auth": [
"bearer"
]
}

The Bearer token sent to your API is prefixed with Bearer in the Authorization header:

"Authorization": "Bearer Q3VyaW91cyBhcmVuJ3QgeW91IQ=="

If you want to change the access token prefix from Bearer, use custom authentication instead.

The bearer token can be set either when you initialize the SDK, or later.

To set the bearer token when you initialize the SDK, use the following code:

The bearer token is set in the SdkConfig object that is passed to the SDK constructor.

src/index.ts
export interface SdkConfig {
token?: string;
...
}

export class ExcitingSoda {
constructor(config: SdkConfig)
...
}
src/example.ts
import { ExcitingSoda } from 'exciting-soda';

const sdk = new ExcitingSoda({
token: process.env.EXCITINGSODA_BEARER_TOKEN
});

To set the bearer token later, use the following code:

To set the bearer token, use the setToken method on the ExcitingSoda class.

src/index.ts
export class ExcitingSoda {
setToken(token: string): void {}
...
}
src/example.ts
import { ExcitingSoda } from 'exciting-soda';

const sdk = new ExcitingSoda();
sdk.setToken('MY_TOKEN');

Custom access token

If your API uses an access token, this can be sent in the Authorization header with every request, along with an optional prefix. To configure custom access token authentication, set the following in your config file:

liblab.config.json
{
"auth": [
"custom"
],
"customizations": {
"authentication": {
"access": {
"prefix": "MY_CUSTOM_PREFIX"
}
}
}
}

The access token can have an optional prefix in the Authorization header. This can be customized in the config file:

liblab.config.json
{
...
"customizations": {
"authentication": {
"access": {
"prefix": "MY_CUSTOM_PREFIX"
}
},
}
...
}

Giving:

"Authorization": "MY_CUSTOM_PREFIX Q3VyaW91cyBhcmVuJ3QgeW91IQ=="

The custom access token can be set either when you initialize the SDK, or later.

To set the custom access token when you initialize the SDK, use the following code:

The custom access token is set in the SdkConfig object that is passed to the SDK constructor.

src/index.ts
export interface SdkConfig {
token?: string;
...
}

export class ExcitingSoda {
constructor(config: SdkConfig)
...
}
src/example.ts
import { ExcitingSoda } from 'exciting-soda';

const sdk = new ExcitingSoda({
token: process.env.EXCITINGSODA_BEARER_TOKEN
});

To set the custom access token later, use the following code:

To set the custom access token, use the setToken method on the ExcitingSoda class.

src/index.ts
export class ExcitingSoda {
setToken(token: string): void {}
...
}
src/example.ts
import { ExcitingSoda } from 'exciting-soda';

const sdk = new ExcitingSoda();
sdk.setToken('MY_TOKEN');

OAuth

liblab OAuth integration focuses on the clientCredentials flow, used for server-to-server communication, such as API authentication. This method is secure, scalable, and aligns with OpenAPI standards for easy implementation.

note

For additional information on how to configure the OpenAPI specification to  use the clientCredentials flow, access the OpenAPI Specification or OAuth 2.0 pages.

The liblab OAuth approach provides seamless API authentication, efficient token management, and flexible scope control, ensuring users can access APIs securely with the correct permissions. The configuration is designed to be adaptable to your needs, whether you require OAuth at a global level or for specific endpoints.

Native OAuth supported SDK languages and versions

TypeScriptJavaPythonC#GoPHP
OAuth support

You can use the OAuth feature with all programming languages via hooks.

liblab is working to integrate the OAuth feature natively into additional programming languages.

liblab OAuth configuration

You can configure OAuth in two ways through the liblab configuration file:

  1. Global Configuration: Set OAuth globally for all API endpoints.
  2. Endpoint-Specific Configuration: Customize OAuth settings for individual endpoints.

1. Global OAuth configuration

To enable OAuth globally for all API endpoints, you can modify the auth array in the liblab config file. Add "oauth" as follows:

liblab.config.json
{
"auth": [
"oauth"
]
}

If the OAuth flow is already correctly defined in the OpenAPI specification, adding the above configuration to liblab's config file is sufficient to enable OAuth for endpoints. The OAuth flow settings must be set using the oauth object under customizations -> authentication in the OpenAPI specification.

You can add any parameters to the OAuth flow through the OpenAPI spec. Any parameters marked as required in the spec must be provided during the SDK initialization.

const sdk = new YourSdk({ 
clientId: "VALID_CLIENT_ID",
clientSecret: "VALID_CLIENT_SECRET",
customParam: "YOUR_CUSTOM_PARAM"
});

const { data } = await sdk.pets.listPets();

To customize OAuth settings, defined in the OpenAPI specification, you have to add parameters under the customization -> authentication -> oauth section. Below is a list of customizable parameters:

Setting  TypeRequired Description
enabledbool✅    Specifies if OAuth is enabled.          
basicbool❌    If true, sends client_id and client_secret as basic authentication in the OAuth request.    
tokenEndpointobject❌    Customizes retrieving and using the access token.  
securitySchemeobject❌      Specifies the security scheme used for OAuth.       

The next code block presents an example of global OAuth configuration:

liblab.config.json
"oauth": {
  "enabled": true,
  "basic": false,
  "tokenEndpoint": {
    "path": "/oauth/token",
    "method": "post",
    "definition": { ... }  // token endpoint definition
  },
  "securityScheme": {
    "name": "mySecurityScheme",
    "definition": { ... }  // security scheme definition
  }
}

tokenEndpoint

The tokenEndpoint options allows you to customize how to retrieve and use the access token. If an endpoint is already defined by the path and method in the OpenAPI specification, this object can override that definition to apply custom OAuth settings. This section is an object with the following options:

Setting  TypeRequired Description
tokenEndpoint.methodstring✅      The HTTP method, post or get, used to retrieve the token. It's only required if the tokenEndpoint is defined.                                      
tokenEndpoint.pathstring✅      The path to use for the token endpoint. It's only required if the tokenEndpoint is defined.                                                          
tokenEndpoint.definitionobject✅      The definition of the token endpoint, using OpenAPI specification syntax. It's only required if the tokenEndpoint is defined.                          

securityScheme

The securityScheme options allows you to specify the security scheme used for OAuth. This section is an object with the following options:

Setting  TypeRequired Description
securityScheme.namestring✅      The name of the security scheme. If it exists in the OpenAPI specification, it will be overwritten. It's only required if the securityScheme is defined.          
securityScheme.definitionobject✅      The definition of the security scheme, following OpenAPI specification syntax. It's only required if the securityScheme is defined.                     

2. Configuring OAuth for specific endpoints

To configure OAuth for specific API endpoints, use the endpointCustomizations feature. This allows you to apply OAuth to individual endpoints while bypassing others.

The next code block presents an example of an endpoint-specific configuration. In this example, OAuth is applied only to the GET /pets endpoint:

liblab.config.json
{
...
  "customizations": {
    "endpointCustomizations": {
      "/pets": {
        "get": {
...
          "security": [
            {
              "<securitySchemaName>": ["read:scope"]
            }
          ]
        }
      }
    }
  }
}

In this case, the GET /pets endpoint requires OAuth authentication with the specified scope read:scope.

Refresh tokens

Supported SDK languages and versions:

TypeScriptJavaPythonC#GoPHP

If your API supports refresh tokens, the liblab generated SDK can use these to ensure the user remains authenticated. In the config file, you can provide the endpoint from your API that is used to refresh the token, as well as the properties on the response object sent in the body of the refresh response to use to read the new tokens.

For example, if this is the endpoint in your spec:

openapi.json
{
"paths": {
"/refreshToken": {
"post": {
"description": "Refresh a short lived access token",
"operationId": "refreshToken",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RefreshTokenInput"
}
}
}
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RefreshTokenPair"
}
}
},
"description": "OK"
}
}
}
},
...
}
}

The request body needs to be an object with a single string property. This property will be used to send the refresh token to the API:

openapi.json
{
"components": {
"schemas": {
"RefreshTokenInput": {
"properties": {
"refreshToken": {
"type": "string"
}
},
"type": "object"
},
...
}
}
}

This single property can have any name, and the value of the refresh token will be set on that property by the SDK when the request is made.

Your spec would also define the response object returned in the body of the /refreshToken response, referred to by the #/components/schemas/RefreshTokenPair schema ref:

openapi.json
{
"components": {
"schemas": {
"RefreshTokenPair": {
"properties": {
"accessToken": {
"type": "string"
},
"refreshToken": {
"type": "string"
}
},
"type": "object"
},
...
}
}
}

In this case, your config file would need to map the /refreshToken endpoint, along with the accessToken and refreshToken properties:

liblab.config.json
{
"customizations": {
"refreshToken": {
"endpoint": "/refreshToken",
"bearerKey": "accessToken",
"refreshKey": "refreshToken"
}
}
}

These values need to match your spec, otherwise the SDK generation will fail.

Once this has been configured, the first time your API is called a refresh token will be requested. On subsequent calls, if the API returns a 401 (unauthorized) response, the SDK will automatically request a new access token using the refresh token, extract the values from the response body, then retry the original request.