Writing a Webhook

1. Writing a Webhook

In order to appropriately handle requests from the FusionAuth event, you must build a simple HTTP Webhook that listens for requests from the FusionAuth event system. Your Webhook must be designed to receive to simple HTTP POST requests with a JSON request body. The HTTP request will be sent using a Content-Type header value of application/json.

Additional headers may be added to the request by adding headers to the Webhook configuration.

1.1. Responses

Your Webhook must handle the RESTful request described above and send back an appropriate status code. Your Webhook must send back to FusionAuth an HTTP response code that indicates whether or not the event was successfully handled or not. If your Webhook handled the event properly, it must send back an HTTP response status code of 200. If there was any type of error or failure, your Webhook must send back an HTTP response status code of 500.

1.2. Configuration

Once your Webhook is complete and listening for events, you must configure your Webhook URL in FusionAuth. To add a webhook navigate to Settings Webhooks. If you have multiple Webhooks configured for a single Application, the transaction setting for the event or the User Action will dictate if FusionAuth will commit the transaction or not.

1.3. Example Code

Here’s a simple example of a Webhook written in Node using Express. In this example, if the event is a user.delete event, this code deletes all of the user’s Todos.

In this example we are also checking the HTTP Authorization header for an API key. Using an API key or some type of authentication helps secure your Webhook to prevent malicious requests. You can configure the API key via the FusionAuth Web Interface or the API using the Headers of the Webhook configuration.

Example Webhook
router.route('/fusionauth-webhook').post((req, res) => {
  const authorization = req.header('Authorization');
  if (authorization !== 'API-KEY') {
    res.status(401).send({
      'errors': [{
        'code': '[notAuthorized]'
      }]
    });
    return;
  }

  const request = req.body;
  if (request.event.type === 'user.delete') {
    todo.deleteAll(request.event.user.id)
      .then(() => {
        res.sendStatus(200);
      })
      .catch(function(err) {
        _handleDatabaseError(res, err);
      });
  }
});