inRiver REST API authentication in HTML templates

Patrick
Patrick

Hi there!

Quick post today about a solution I keep forgetting - authenticating inRiver REST API calls from HTML templates using the current user's credentials.

The Problem

When making REST API calls from custom HTML templates in inRiver, you need to authenticate using the current user's session/API key. Without proper configuration, the authentication context won't be passed along with your requests, resulting in failed API calls.

The Solution

The key is to configure your jQuery AJAX calls with the correct cross-domain and credential settings:

$.ajax({
  url: "your-rest-api-endpoint",
  xhrFields: {
    withCredentials: true,
  },
  crossDomain: true,
  // ... rest of your AJAX configuration
});

The withCredentials: true property ensures that the browser includes credentials (cookies, authorization headers, or TLS client certificates) in the cross-origin request. The crossDomain: true flag explicitly marks this as a cross-domain request, which is necessary even when calling inRiver's own API from within the application.

Example

Here's a complete example making a REST API call:

$.ajax({
  url: "/api/v1.0.0/entities/123",
  method: "GET",
  xhrFields: {
    withCredentials: true,
  },
  crossDomain: true,
  success: function (data) {
    console.log("Entity data:", data);
  },
  error: function (xhr, status, error) {
    console.error("API call failed:", error);
  },
});

Using Native Fetch API

If you prefer using the modern Fetch API instead of jQuery, the equivalent configuration uses the credentials option:

fetch("/api/v1.0.0/entities/123", {
  method: "GET",
  credentials: "include",
})
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then((data) => {
    console.log("Entity data:", data);
  })
  .catch((error) => {
    console.error("API call failed:", error);
  });

The credentials: "include" option is the Fetch API equivalent of jQuery's withCredentials: true, ensuring that cookies and authentication credentials are sent with the request.

With this configuration, your REST API calls will authenticate using the current user's credentials, allowing you to build custom HTML templates that interact with the inRiver API seamlessly.

Cheers!