Using the API to login and direct to a page

One possible use of the API to support integrations with third party systems is to use the API to seamlessly log a user in to their intranet and then navigate them to a page on the intranet.

The single use token, and redirector page allows you to easily convert an API authenticated user into a web authenticated user, without having to go through the login processes again.

The example PHP code shown below demonstrates this by first logging the user into the API, and then creating a single use token for the redirector page and finally navigating the user to the target page on the intranet.

For information on how to find the API domain and the tenant Guid for your instance please see How to get API information

<?
// Get variables for API calls
$apiDomain = "YOUR API DOMAIN";
$webDomain = "YOUR WEB DOMAIN";
$tenantGuid = "YOUR TENANT GUID";

$pageUrl = "YOUR TARGET PAGE";

$user = "USERNAME";
$pw = "PASSWORD";

$accessToken = "";


// login to the API
$resp = callApi("/token", "username=".$user."&password=".$pw."&grant_type=password");
$accessToken = $resp['access_token'];

// get a one time use token
$resp = callApi("/api/logintoken","");
$oneTimeToken = $resp['login_token'];

// redirect to redirector
$returnUrl = $webDomain.$pageUrl;
$url = $webDomain."/redirector?token=".$oneTimeToken."&returnUrl=".urlencode($returnUrl);

header("Location: ".$url);


// helper functions
function callApi($url, $body){
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $GLOBALS['domain'].$url);

  if($body != ""){
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  }

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $headers = [
    'Content-type: application/x-www-form-urlencoded',
    'X-Tenant: '.$GLOBALS['tenantGuid'],
    'Authorization: Bearer '.$GLOBALS['accessToken']
  ];

  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  $server_output = curl_exec($ch);

  curl_close($ch);

  return json_decode($server_output, true);
}

?>