Third Party Integration Guide

The TForce Freight API third party integration guide is a high-level walkthrough of how the integration points in our API ecosystem work together to empower TForce Freight customers to enroll their accounts with your organization's application and begin using your application to access and update their account information.

If your organization only needs access to its own account information in the application you'd like to develop, visit our End User Integration Guide instead.

Overview

The TForce Freight API is secured by the Microsoft Identity Platform using industry-standard OpenID Connect and OAuth protocols to provide authentication and authorization for your requests. Using your developer portal profile, you can discover and configure the details needed to successfully create requests to the APIs published here.

The TForce Freight Customer Identity and Access Management (CIAM) platform is not intended to directly serve as an identity provider for your user-facing client application. Rather, our application portal provides the infrastructure needed to guide your users through the registration and onboarding process for your application, and instead, uses a webhook publisher/subscriber model to provide your application with the information required to begin accessing a TForce Freight customer's account information via web API. This guide details the user experience of this onboarding process, the requirements for configuring your application registration in our developer portal, how to prepare your application to receive webhook event payloads, as well as how to use those published events to gain access to newly onboarded customers' TForce Freight account information.

User Onboarding Flow

Many interactions with the TForce Freight CIAM platform are simplified and managed through features of the application portal. This portal serves as the primary mechanism for interactively onboarding new users to your application. It provides user experiences for granting consent to your application to access data on their behalf as well as revoking that consent at a future time, and it publishes events to your application at a configured webhook subscriber endpoint to notify your application of changes that will impact its integration to our APIs.

While future sections describe many of the interactions that third party apps might have with the application portal, it is useful to understand the overarching user experience of the third party app enrollment flow and some of the behaviors that arise from user interactions with the system during that flow. The steps of the third party user onboarding flow are as follows:

  1. Your application displays the sign-up and login links provided on your profile's OAuth Client dialog to the user to sign-up for a new TForce Freight customer account or log into an existing TForce Freight account. Your application provides a reference identifier in this link for the operation, e.g. a request ID or local user ID, to allow for future correlation of the onboarding operation.

    ⚠️ IMPORTANT
    It is recommended that these links open in a new window using the anchor target="_blank" attribute as the user will not be redirected back to your application once enrollment is complete.
  2. [Optional] The user completes the account creation process in the TForce Freight CIAM platform and is automatically logged into the TForce Freight application portal.

  3. After logging in to the TForce Freight application portal using the TForce Freight CIAM platform, the user is prompted to confirm the account password once more and grant consent for your application to access TForce Freight account data on her or his behalf.

    ℹ️ NOTE
    During this step, the consent prompt experience is rendered with elements of the application registration that you configured in your profile OAuth Client dialog. This is explained in further detail below.
  4. Once consent is granted, the application portal generates a UserOnboardedEvent webhook payload detailed in a following section that contains the reference ID provided in your application link, as well as an operation ID from the TForce Freight CIAM platform for support reference. This payload will be published to the webhook subscriber endpoint you have configured using a bearer token in the request Authorization header that can be exchanged with the TForce Freight CIAM platform for an access token and refresh token. This access token can be used in requests to TForce Freight APIs to obtain the user's data and refreshed once its lifetime expires.

Be mindful that while consent is immediately established for your application to access the user's data, TForce Freight user account creation may not be meaningfully complete until it is configured by a representative to obtain the customer's appropriate rating and shipping information in response to API requests.

Configuring Your Application

To configure your application, begin by navigating to your developer portal profile and clicking the Configure My Client button. The OAuth Client dialog contains various configuration elements that drive different backend and frontend behaviors described below by section.

Your OAuth Client

This section provides presentation configuration for all consent experiences related to your app, both when displaying initial consent requests to users as well as presenting users with a list of apps to which they've granted consent to access their data. Provide the following information in this section as described:

  • Upload new logo: Replaces the user-facing logo for the application.

    ❔ TIP
    For best results, observe the requirements provided on the file upload tooltip.

    The image file for the logo must meet the following requirements: Image dimensions of 215 x 215 pixels. Uses file type .bmp, .jpg, or .png. File size less than 100 KB.

    It is also advisable to provide adequate proportional negative space around your logo mark in accordance with your corporate brand guidance.
  • Display Name: The user-facing display name for the application.

  • Home page URL: The URL to the application's home page or the URL where users can sign-in and use this application.

  • Terms of service URL: A link to a webpage containing the application's terms of service.

  • Privacy statement URL: A link to a webpage containing this application's privacy statement.

Application Integration

Information in this section is largely intended to assist with providing your application enrollment links to users and validate JSON Web Tokens provided in webhook request payloads.

There is one configurable field to note in this section:

  • Webhook URL: A URL for the endpoint that will receive published events from the TForce Freight API Gateway, e.g. a UserOnboardedEvent.

The Sign Up URL and Login URL fields display a {referenceId} segment that should be replaced by your application when generating the hyperlink element of your UI. This is an identifier that will be included in any related webhook payloads to help you identify the original request, user, or other resource understood by your application to correlate the incoming event and its data to your local system. For instance, your application may include a reference ID containing the account identifier for the local user in your application so that when a webhook event is dispatched with the onboarded user's information, you can store information such as the TForce Freight user identifier, user access token, or user refresh token in the local user's profile.

OAuth Client Secrets

This section provides features to review and maintain client secrets for OAuth protocol exchanges with the TForce Freight CIAM platform. When creating a new secret, you can label your secrets with a name in the Description field to remind you which subsystem may use the secret to request tokens, as well as provide a lifetime in the Expires field when the secret will automatically expire.

CRITICAL
Client secret values can only be viewed immediately following creation. Be sure to save your newly created secrets before leaving this page.

The Secret ID column in the secrets table is only an informational identifier and will never be used in in OAuth protocol exchanges. If a secret is expired or has become compromised, it can be deleted using the delete button at the end of each secret detail row.

Creating a Webhook Endpoint

Events that may be of interest to your application will be published to the webhook endpoint you have configured in your profile OAuth Client dialog. An example webhook request in response to a new user onboarding to a third party application is detailed below.

POST /relative/path/to/webhook HTTP/1.1
Host: <developer_app_host>
Content-Type: application/cloudevents-batch+json
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ii1LSTNROW5OUjdiUm9meG1lWm9YcWJIWkdldyIsImtpZCI6Ii1LSTNROW5OUjdiUm9meG1lWm9YcWJIWkdldyJ9...

[
  {
    "specversion": "1.0",
    "id": "e3794457-117a-43d8-b2bf-32f3f8efde93",
    "time": "2023-06-21T10:12:56.4470101-06:00",
    "subject": "f6ed8ba5-6e23-417b-beaf-fe23d089a8f6",
    "source": "https://api.tforcefreight.com/cloudevents",
    "type": "TForceFreight.CloudEvents.Api.UserOnboardedEvent/v1",
    "datacontenttype": "application/json",
    "data": {
        "referenceId": "e36758a9-c7a1-4c3d-8f0b-0236bd041185",
        "operationId": "fe96a3d3e4f08835261edbc002d0e978"
    }
  }
]

The value provided in the Authorization header of this request contains a signed JSON Web Token using the Bearer scheme that can be validated using the values in the Application Integration section of your OAuth Client dialog. Validation parameters for this token's claims are outlined in the following section.

The body of the webhook request will contain a payload describing the event that occurred which your application may wish to process. The most common of these events, the UserOnboardedEvent, is described further below.

Validating the Incoming Token

The JWT token provided in the request as a Bearer token authorization scheme can be validated both via its signature to ensure it has not been tampered with, as well as by inspecting the following claim values to ensure they match expectations:

  • aud: The audience claim should match the following URI, replacing the indicated portion with the client ID from your OAuth Client dialog.

    https://tffproduction.onmicrosoft.com/{clientId}
  • iss: The issuer claim should match the value in the OpenID Connect metadata document linked in your OAuth Client dialog.

    https://sts.windows.net/ca4f5969-c10f-40d4-8127-e74b691f95de/
  • appid: The client application identifier claim will always match the value for the TForce Freight application portal.

    ed4659ad-1015-4e23-a5d4-16e90d215142
  • scp: The scope claim is only guaranteed to be present when the event originates from an interactive operation initiated by an authenticated user. The scope claim value may include a space-separated list of claim value tokens. The claim value should always contain the below substring when the claim is present.

    WebhookEvent.Publish
  • roles: The roles claim is only guaranteed to be present when the event originates from an unattended scenario that is not in direct response to an authenticated user's actions. The roles claim is expressed as an array of values. The claim value array should always contain the below string when the claim collection is present.

    WebhookEvent.PublishUnattended
    ℹ️ NOTE
    This claim is not currently in use.
  • tid: The tenant ID claim should always match the value for the TForce Freight CIAM platform.

    ca4f5969-c10f-40d4-8127-e74b691f95de

To validate the JWT signature, utilize the JSON Web Key Set metadata document referenced in the OpenID Connect configuration metadata document that is linked in your OAuth Client dialog. Most API software development kits will include libraries for validating JWT signatures and claims using middleware in your request processing pipeline. For a list of suggested JWT validation libraries, visit this library reference or consult the documentation for your chosen API development platform.

Webhook Event Body

When a user grants consent for your application to access data on her or his behalf, the application portal will dispatch a UserOnboardedEvent to your webhook endpoint. All events dispatched to your webhook endpoint will conform to the CloudEvents 1.0.2 specification to provide for interoperability with various platform as a service offerings and SDKs. Whenever possible, these payloads will utilize the application/cloudevents-batch+json format in order to allow dispatching all versions of an event simultaneously. The important data communicated in the UserOnboardedEvent body is as follows:

  • type: The type and version identifier of the event. The current value for the UserOnboardedEvent is

    TForceFreight.CloudEvents.Api.UserOnboardedEvent/v1
  • subject: An identifier for the source of the event, in this case, the identifier for the TForce Freight user account.

  • data.referenceId: The identifier provided by your application in the sign up or login link used to onboard the user.

  • data.operationId: The identifier for the operation in the TForce Freight telemetry system for use in any troubleshooting or support requests.

The referenceId property of the UserOnboardedEvent should be combined with the following section to obtain tokens for the newly onboarded user and store them in reference to the user account in your system. Optionally, you can also retain the subject identifier from the TForce Freight CIAM platform to assist in identifying any issues in retrieving the user's data.

Obtaining an Access Token

The JWT provided to secure the UserOnboardedEvent webhook request can be utilized in a token exchange with the TForce Freight CIAM platform to retrieve an access token and refresh token that will grant access to data associated with the user who enrolled with your application.

The TForce Freight CIAM platform utilizes the On-Behalf-Of flow provided by Azure Active Directory to generate these tokens. In the scenario described in the flow documentation, the client application is the TForce Freight application portal, your application is a middle-tier API, and the downstream API is the TForce Freight API Gateway. This flow allows for long-lived refresh windows for confidential clients to obtain new access tokens as needed during a 90-day period after the last on-behalf-of token request.

As this flow is provided by the Microsoft Identity Platform, the Microsoft Authentication Library (MSAL) is an excellent tool to leverage in order to simplify your consumption of the OAuth exchange and manage the lifetime of the returned tokens. The library is available to multiple API development languages such as C#, Java, Node.js, and Python. Additional links to code samples for this flow are available at the MSAL samples directory.

The remainder of this article will explain how to consume the flow in the absence of an acceptable library implementation for your API development stack.

Creating a Token Request

A token request for the on-behalf-of flow composes the information from the OAuth Client dialog in your profile with the JWT provided in the UserOnboardedEvent payload to receive an access token and refresh token for a user in response. The JWT used in the token request will have a lifetime of less than 90 minutes, based on when it was issued during the user's onboarding. In general, your application should attempt to process these webhook events in a timely fashion to avoid expiry of the exchange token provided during the request.

The on-behalf-of flow utilizes the OAuth token endpoint of the TForce Freight CIAM platform, taking the following parameters as application/x-www-form-urlencoded content at the POST HTTP method of the token endpoint:

  • client_id: The Client ID of your application from the OAuth Client dialog.

  • client_secret: A secret you created in the OAuth Client Secrets section of the OAuth Client dialog.

  • grant_type: Use the value urn:ietf:params:oauth:grant-type:jwt-bearer to indicate you wish to exchange the existing access token provided in the webhook payload for one granting access to the downstream TForce Freight API gateway.

  • assertion: The raw JWT value provided as a bearer token in the Authorization header of the UserOnboardedEvent webhook request.

  • scope: Use the Scope value from the Application Integration section your OAuth Client dialog to indicate that you require access to the Develolper.All scope for the user on the TForce Freight API gateway in order to generate an access token in response. Ensure you include the space-separated offline_access scope as well to receive a refresh token in the response that will allow obtaining a new access token after the current access token lifetime expires.

  • requested_token_use: Use the value on_behalf_of to invoke the token exchange flow for access to the TForce Freight API gateway on the user's behalf.

A sample request for the on-behalf-of flow follows. Use the Token Endpoint from the Application Integration section of your OAuth Client dialog as the URL for this request.

//line breaks for legibility only

POST /ca4f5969-c10f-40d4-8127-e74b691f95de/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

client_id=3c29446e-153e-4b92-8f06-c453f117b645
&client_secret=3e04~5e12339444d1852d73bb33e9.3cf2
&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer
&assertion=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ii1LSTNROW5OUjdiUm9meG1lWm9YcWJIWkdldyIsImtpZCI6Ii1LSTNROW5OUjdiUm9meG1lWm9YcWJIWkdldyJ9...
&scope=https://tffproduction.onmicrosoft.com/f06cb173-a8e6-44ad-89a1-06c1070a1f62/Developer.All+offline_access
&requested_token_use=on_behalf_of

If you have included both scopes indicated above, along with valid OAuth client information and exchange token, the response should be similar to the following sample:

Content-Type: application/json

{
"token_type": "Bearer",
"scope": "https://tffproduction.onmicrosoft.com/f06cb173-a8e6-44ad-89a1-06c1070a1f62/Developer.All",
"expires_in": 3599,
"ext_expires_in": 3599,
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ii1LSTNROW5OUjdiUm9meG1lWm9YcWJIWkdldyJ9...",
"refresh_token": "0.AR0AaVlPyg_B1ECBJ-dLaR-V3hNM2J1VWJ1LgNiLMPy08rcdACk..."
}

Processing and persisting values of the token response is detailed in the following section.

Managing Tokens

When implementing your integration with the TForce Freight API gateway, you must manage aspects of storing, retrieving, and refreshing the tokens that grant you access to user data.

The value of the access_token property can be used immediately for requests on behalf of the newly enrolled user to the TForce Freight API gateway. Once the lifetime of the token has expired, the value of the refresh_token property can be used in a subsequent token request to obtain a new access token. This request will be explained in detail further on. Your application should typically store and associate both of these values with the local user's account for later use.

Access tokens issued by the TForce Freight CIAM platform are typically lived for one hour. This is indicated in the token response via the expires_in property. However, to ensure the most accurate understanding of the token's lifetime, decode and deserialize the access token you receive in the token response, and determine the expiry time by calculating it from the Unix epoch datetime expressed by the exp claim value. It may be helpful to store this information along with a user's access and refresh tokens to speed evaluation of the token lifetime when communicating with the TForce Freight API gateway.

In addition, you may wish to record a datetime 90 days from the Unix epoch datetime expressed by the access token's iat (issued at) claim value, as the refresh token provided in the response will become invalid 90 days after the access token was issued. If a new refresh token is not claimed before this date, it will be necessary for your application to recover its access rights for the user as described in the following section.

When creating a request to the TForce Freight API gateway, inspect the expiry of the access token you have stored for the user. If the token is expired, use the most recent refresh token to obtain and replace the user's access and refresh tokens by issuing a refresh request to the token endpoint.

The parameters should be sent using the POST HTTP method as application/x-www-form-urlencoded content with the following parameters:

  • client_id: The Client ID of your application from the OAuth Client dialog.

  • client_secret: A secret you created in the OAuth Client Secrets section of the OAuth Client dialog.

  • grant_type: Use the value refresh_token to indicate the desire to issue a new access token using the refresh flow.

  • scope: Use the Scope value from the Application Integration section your OAuth Client dialog to indicate that you require access to the Develolper.All scope for the user on the TForce Freight API gateway in order to generate an access token in response. Ensure you include the space-separated offline_access scope as well to receive a refresh token in the response that will allow obtaining a new access token after the current access token lifetime expires.

  • refresh_token: Provide the refresh token you have stored for the user in this parameter.

//line breaks for legibility only

POST /ca4f5969-c10f-40d4-8127-e74b691f95de/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

client_id=3c29446e-153e-4b92-8f06-c453f117b645
&client_secret=3e04~5e12339444d1852d73bb33e9.3cf2
&grant_type=refresh_token
&refresh_token=0.AR0AaVlPyg_B1ECBJ-dLaR-V3hNM2J1VWJ1LgNiLMPy08rcdACk...
&scope=https://tffproduction.onmicrosoft.com/f06cb173-a8e6-44ad-89a1-06c1070a1f62/Developer.All+offline_access

The token endpoint response will match the same format described in the previous section for on-behalf-of token exchange. Ensure you update all token and expiry data you have retained for the user using the information in this response.

Once you have a token with a valid lifetime, create your request to the TForce Freight API gateway, appending an Authorization header using the Bearer scheme, as below:

Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ii1LSTNROW5OUjdiUm9meG1lWm9YcWJIWkdldyJ9...
Recovering Access Rights

If the lifetime of the refresh token you have stored for a user has expired and you require access to their account data, it is necessary to forward the user to the Login URL displayed in your OAuth Client dialog's Application Integration section. This will prompt the user to reaffirm their consent for your application to access their TForce Freight account data and publish a new UserOnboardedEvent to your webhook endpoint as described above. From there, your application should be able to recover from the expired state.

If you would prefer to avoid this scenario, create a nightly job to interrogate user data for expiring refresh tokens, and issue a refresh request to the token endpoint before the refresh token lifetime ends, such as for refresh tokens reaching the 89th day of their life.

Additional Resources

Microsoft identity platform and OAuth 2.0 On-Behalf-Of flow (Link)

Overview of the Microsoft Authentication Library (MSAL) (Link)

CloudEvents (Link)