Call an API from a Lambda

On this page
Essentials plan required

This feature requires at least an Essentials plan.

Lambda HTTP Connect allows you to make HTTP requests from within a lambda with fetch(). Lambdas can contact any URL accessible from your FusionAuth instance.

Use HTTP Connect to read data from an external system into token claims or a user profile. You can also push profile data from FusionAuth to an external system.

The following video shows Lambda HTTP Connect in more detail:

Play

Example Lambda#

To make a request, call fetch() with the following arguments:

  • A URL string.
  • Optionally, an options object that configures the request.

The following lambda makes an HTTP GET request to a billing API at billing.example.com. The lambda reads the API key from a secret and sets short timeouts, so a slow API doesn't hold up login. The lambda adds the tier from the response to the JWT as a namespaced claim:

A lambda that adds a claim from an external API.
// adds the user's subscription tier from a billing API, and falls back to basic when the API fails
function populate(jwt, user, registration, context) {
  var response = fetch('https://billing.example.com/api/customers/' + encodeURIComponent(user.id), {
    method: 'GET',
    headers: {
      'Accept': 'application/json',
      'Authorization': 'Bearer ' + context.services.secrets.get('billing-api-key')
    },
    connectTimeout: 1000,
    readTimeout: 1500
  });

  // a status of -1 means FusionAuth could not reach the API
  if (response.status !== 200) {
    console.error('Could not read the billing tier for user ' + user.id + '. The billing API returned status ' + response.status + '.');
    jwt['https://example.com/tier'] = 'basic';
    return;
  }

  jwt['https://example.com/tier'] = JSON.parse(response.body).tier || 'basic';
}

fetch() returns a response with a status and a body string. Parse the body with JSON.parse(). When FusionAuth can't reach the API, the response has a status of -1. The lambda checks the status before reading the body, and adds a default tier when the request fails. Login still succeeds.

You can also call FusionAuth APIs with a valid API key.

The following lambda adds the names of the user's groups to the access token. The user.memberships argument holds only group Ids, so the lambda calls the Groups API for the names. The lambda reads a FusionAuth API key from a lambda secret named fusionauth-api-key. Lambda secrets are available in FusionAuth 1.64.0 and later. The lambda calls the local FusionAuth HTTP port, 9012 by default, so the request doesn't leave the server. When the call fails, the lambda logs the error and issues the token with an empty groups claim.

A lambda that adds group names to the access token.
// adds the names of the user's groups to the access token
function populate(jwt, user, registration, context) {
  var groupIds = user.memberships.map(function (membership) {
    return membership.groupId;
  });
  if (groupIds.length === 0) {
    jwt.groups = [];
    return;
  }

  var response = fetch('http://localhost:9012/api/group', {
    method: 'GET',
    headers: {
      'Authorization': context.services.secrets.get('fusionauth-api-key')
    }
  });

  // issue the token without groups instead of failing the login
  if (response.status !== 200) {
    console.error('Could not read groups. The Groups API returned status ' + response.status + '.');
    jwt.groups = [];
    return;
  }

  jwt.groups = JSON.parse(response.body).groups
    .filter(function (group) {
      return groupIds.indexOf(group.id) !== -1;
    })
    .map(function (group) {
      return group.name;
    });
}

Use the local FusionAuth HTTP port for every FusionAuth API call in a lambda. The fusionauth-app.http-local.port setting controls the port, which defaults to 9012. The local port reduces network contention and improves performance.

Options#

Timeouts#

Available since 1.55.1

External requests in a lambda must return quickly. A lambda blocks the FusionAuth request until the lambda completes, so every delay adds latency to the user interaction. A slow request can reduce FusionAuth performance or cause errors.

Lambdas use default connect and read timeouts of 2 seconds. To change a timeout for a slow request, pass an options object as the second argument to fetch(). Set connectTimeout or readTimeout to an integer number of milliseconds:

var response = fetch("https://api.example.com/api/status", {
    method: "GET",
    connectTimeout: 42000,   // 42,000 ms, or 42 seconds
    readTimeout: 42000       // 42,000 ms, or 42 seconds
  });

Body#

By default, fetch() sends no request body. To send a body, set body to a string in the options object:

var response = fetch("https://api.example.com/api/status", {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ status: "active" })
  });

Set a Content-Type header that matches the body. Without the header, fetch() labels the body as form data. See Headers.

Method#

By default, fetch() sends an HTTP GET request. To use a different method, set method in the options object to an HTTP method name as a string:

var response = fetch("https://api.example.com/api/status", {
    method: "DELETE"
  });

Headers#

By default, fetch() sends the following request headers:

  • Accept: */*
  • Connection: keep-alive
  • Host: the host of the URL
  • User-Agent: Restify (https://github.com/inversoft/restify)

When the request has a body, fetch() also sends Content-Length. Without a Content-Type header, fetch() sends Content-Type: application/x-www-form-urlencoded, even when the body is JSON.

To send other headers, or to replace a default header, set headers in the options object:

var response = fetch("https://api.example.com/api/status", {
  headers: {
    "Accept": "application/json",
    "Authorization": "Bearer " + context.services.secrets.get("status-api-key")
  }
});

To send a header several times, set the header value to an array of strings, such as "X-Tag": ["a", "b"].

You can provide request headers in the following ways:

  • A plain object:

    headers: {
       "Content-Type": "application/json"
    }
    
  • A Headers object built from a plain object:

    headers: new Headers({
       "Content-Type": "application/json"
    })
    
  • A Headers object built from an array of name and value pairs:

    headers: new Headers([
        ["Content-Type", "application/json"]
    ])
    

The lambda Headers object has no methods such as append() or set(). Pass every header to the constructor.

Response#

fetch() returns an object that contains the following fields:

headers
  • Type: Object

The headers returned by the response. The keys of this object are the header names. Header lookups ignore case, so headers['content-type'] and headers['Content-Type'] return the same value. A header with several values returns an array.

status
  • Type: Integer

The HTTP status code of the response.

body
  • Type: String

The body of the response.

Securing API Keys In Lambdas#

Available since 1.64.0

To securely store secret values used in lambdas, like API keys and application passwords, use a lambda secret. To create a secret, open the Admin UI and navigate to Settings -> Key Master .

To access secrets, use the context parameter. Pass a secret name to context.services.secrets.get('<secret-name>') to retrieve the secret value as a string:

function populate(jwt, user, registration, context) {
  var apiKey = context.services.secrets.get('my-api-key');
  if (apiKey) {
    jwt.apiKeyPresent = true;
  }
}

Lambda HTTP Connect Limitations#

Don't call a FusionAuth API that invokes the calling lambda. FusionAuth rejects the recursive call with a 400 response. For example, don't call the Login APIThe FusionAuth API that logs a user in without the hosted login pages. from a JWT populate lambda.

The lambda fetch() method doesn't implement the entire fetch API that browsers provide. The first argument must be a string. fetch() returns the response synchronously, and the response has no json() method or ok field.