Skip to main content

Destinations

SAP Business Technology Platform (SAP BTP) provides the concept of destinations for convenient communication between SAP BTP and other systems. A destination is an object with the following information, among others:

Destinations are managed separately from applications on SAP BTP and can be retrieved through the destination service at runtime. Some reasons to separate destinations and the application are:

  • You can securely store authentication information that should not be part of the application code.
  • You can update resource locations without touching the application code.
  • Different customers may want to configure different systems.
  • Multiple applications might want to access the same systems.

The SAP Cloud SDK helps you to authenticate against the destination service and retrieve destinations into your application.

The SAP Cloud SDK supports OData and OpenAPI services. For both service types, the execute() method triggers a request to a target system. For OData services, you can invoke the method as:

const { businessPartnerApi } = businessPartnerService();
const responseOData = await businessPartnerApi
.requestBuilder()
.getAll()
.execute(myDestination);

Similarly for OpenAPI:

const responseOpenApi = await MyApi.myFunction().execute(myDestination);

myDestination is an SAP Cloud SDK representation of a destination. The given request is executed against myDestination.

For the rest of the document, you will learn about the different options on destination lookup. All statements apply equally to OData- and OpenAPI-based services.

Creating Destinations Manually

caution

This option is not recommended for productive use as you would lose the benefits of separating destinations from applications.

You can construct a destination object manually and pass the destination information directly to the execute() method. A manually constructed destination requires at least a url property.

MyRequest.execute({ url: 'https://example.com' });

Referencing Destinations by Name

Instead of defining your destination manually, you can reference it by a name:

MyRequest.execute({ destinationName: 'myDestination' });

The SAP Cloud SDK searches for the destination by its name in the following locations and order:

  1. local environment variables
  2. destination registered in the SAP Cloud SDK
  3. service binding environment variables
  4. SAP BTP's destination service

The search stops once a matching destination is found, even if other locations may contain another matching destination.

Local Environment Variable

caution

This option should only be used for testing purposes in a local environment outside the SAP BTP where no destination services are available. Use Register Destination to cache destinations in production.

The destinations environment variable is used for the destination lookup in the aforementioned order if they are presented. The value of the environment variable is expected to be a stringified JSON array, where the items adhere to the Destination interface.

Example:

"[{\"name\": \"TESTINATION\", \"url\": \"http://url.hana.ondemand.com\", \"username\": \"DUMMY_USER\", \"password\": \"EXAMPLE_PASSWORD\"}]"

The SAP Cloud SDK provides a setTestDestination() function to add a destination to the environment variable for the current process programmatically. It takes a destination object, transforms it to a JSON object, and adds it to process.env.destinations.

import { setTestDestination } from '@sap-cloud-sdk/test-util';

setTestDestination({
authentication: 'NoAuthentication',
name: 'TESTINATION',
isTrustingAllCertificates: false,
url: 'https://mys4hana.com'
});

The above example sets a destination with the name TESTINATION. At runtime, the SAP Cloud SDK will check the environment variable for a destination with the given name and use it if present.

The SAP Cloud SDK also offers a mockTestDestination() method, which reads in a systems.json and credentials.json to create destinations. The advantage of files is that they can be excluded from the repository since they contain sensitive information.

caution

Note that this approach is not suitable for multi-tenant scenarios, because only the destination service can return destinations for different tenants.

Due to security concerns, the forwardAuthToken option is ignored and the authTokens is always empty.

Register Destination

The destination service should always be used in production to fetch a destination.

Each call to the destination service will introduce a small time overhead. This can be avoided with a cache for cases like very frequent service-to-service communication or when the destination needs no authentication at all.

import { registerDestination } from '@sap-cloud-sdk/connectivity';

const destination = {
name: 'MY-DESTINATION',
url: 'https://mys4hana.com'
};

registerDestination(destination, options);

MyRequest.execute({ destinationName: 'MY-DESTINATION' });

Functions such as execute() and executeHttpRequest() call the getDestination() function internally for the destination lookup. During the lookup, if a registered destination is found, the lookup is stopped, and the call to the destination service is avoided.

caution

You can register a full destination object, including authentication, but it is not recommended to store authentication information in the registered destination. Instead, you should enable token forwarding on the destination.

With token forwarding the token used to execute the request is sent to the destination:

const destination = {
name: 'FORWARD-DESTINATION',
url: 'https://mys4hana.com',
forwardAuthToken: true
};

registerDestination(destination, options);

MyRequest.execute({
destinationName: 'FORWARD-DESTINATION',
jwt: 'forwardedJwt'
});

This only works if your target system accepts unchanged JWTs. Use the destination service if a transformation is needed, e.g., OAuth to SamlBearer.

Note that the registerDestination() function is tenant-aware. The destination cache guide describes the cache options used by the registerDestination() function.

Service Binding Environment Variables

The service credentials (also known as the VCAP_SERVICES environment variable) represent services bound to the application. If you want to consume such a service, the SAP Cloud SDK can create a destination from the service binding for you. You do not need to create a dedicated destination in the destination service. Provide the name of the service instance as the destination name and the SAP Cloud SDK will:

  • Find the service binding with the given name
  • Extract the URL from the service binding
  • Fetch a client-credential-grant token if needed
  • Return a destination containing the token and URL

If you created a binding for the workflow service:

{
"VCAP_SERVICES": {
"workflow": [
{
"label": "workflow",
"plan": "standard",
"name": "my-workflow-service",
"tags": [],
"instance_name": "my-workflow-service",
"credentials": {
// ...
}
}
]
}
}

Call the service API using the instance name my-workflow-service:

import { WorkflowDefinitionsApi } from './generated/SAP_CP_Workflow_CF';

WorkflowDefinitionsApi.queryDefinitions().execute({
destinationName: 'my-workflow-service'
});

The following services are supported out of the box:

  • business-logging
  • s4-hana-cloud
  • destination
  • saas-registry
  • workflow
  • service-manager
  • xsuaa

If you need the destination for another custom service, create a function with ServiceBindingTransformFunction type to transform the Service interface into the Destination interface. Pass the function with the serviceBindingTransformFn property in the DestinationFetchOptions argument.

For example:

const serviceBindingTransformFn = async (service: Service) => ({
url: service.credentials.sys
});

MyRequest.execute({
destinationName: 'my-service-name',
serviceBindingTransformFn
});

More advanced examples with service token fetching can be found in service-binding-to-destination.ts.

You can also consider creating a feature request. Contributions providing transform functions are highly welcome.

The execute() or getDestination() function try multiple steps to retrieve a destination, as discussed in the beginning. If you want to consider only the service bindings, call the destinationForServiceBinding() function with the service name and options.

const destination = destinationForServiceBinding('my-service-name', {
serviceBindingTransformFn,
jwt: 'jwt',
useCache: false
});

Destination Service

In a productive environment, you will use a Destination service to retrieve destinations.

Authentication and JSON Web Token Retrieval

To access the destination service, the SAP Cloud SDK will first fetch an access token from the XSUAA service. The token retrieved from the XSUAA service is used to make a call to the destination service and receive the destinations. The destination service returns a destination with all relevant authentication information depending on the used authentication flow. Listed below are the SDK-supported authentication flows, categorized based on whether a user JWT (jwt property in destination fetch options) is required to retrieve a destination.

  • A user JWT is not required

    • NoAuthentication
    • BasicAuthentication
    • OAuth2ClientCredentials
    • OAuth2Password
    • ClientCertificateAuthentication
    • OAuth2RefreshToken
  • A user JWT is required

    • OAuth2UserTokenExchange
    • OAuth2JWTBearer
    • OAuth2SAMLBearerAssertion
    • PrincipalPropagation

The SAP Cloud SDK automatically parses the response of the destination service and uses the provided authentication information for the request to the target system. For a simple service, this would be the end of the story.

Multi-Tenancy

However, the destination service is special in the way that it is a tenant-aware service. Such services make it possible to build multi-tenant applications. So, what defines a tenant-aware service?

Assume you want to build an application showing the five newest business partners in an SAP S/4HANA system. You want to offer this application as a service to customers. Of course, you want to make this service cost-efficient and host it only once and let multiple customers use it. This means your service needs to return the data related to specific customers. A customer is represented by an account on the SAP BTP. A service considering that account is a tenant-aware service.

Tenant-aware services on the SAP BTP are offered to customers via a subscription which works on a high level as follows: If a customer wants to use a service, a subscription is created linking the customer account and the one account hosting the service. In the following, the term "subscriber account" will be used for the accounts using a service and "provider account" for the one hosting it.

For simplicity, an optional argument of the destination lookup has been neglected in the beginning:

MyRequest.execute({ destinationName: 'myDestination', jwt: 'yourJWT' });

The jwt argument takes the JSON web token (JWT) issued by an XSUAA as input. Additional information on how to retrieve JWTs can be found here. This token contains a field zid holding the tenant id, which will be used in the lookup process. The lookup process done by the SAP Cloud SDK involves the following steps:

  • Request an access token for the destination service and a given tenant ID from the XSUAA.
  • Due to the subscription between provider and subscriber, the XSUAA is allowed to issue the token.
  • The token allows for calling the destination service on behalf of the given tenant. The tenant and service information is encoded in the access token.
  • Make a call to the destination service using the obtained access token.
  • The destination maintained in the given tenant is returned.

If no token is given or the destination is not found in the subscriber account, the provider account is used as a fallback. To control this fallback behavior, a selection strategy can be passed to the destination lookup:

MyRequest.execute({
destinationName: 'myDestination',
jwt: 'yourJWT',
selectionStrategy: 'alwaysSubscriber'
});

The SAP Cloud SDK defines the following selection strategies:

  • alwaysSubscriber: Only try to get destinations from the subscriber account. A valid JWT is mandatory to receive something.
  • alwaysProvider: Only try to get the destination from the provider account. A JWT is not needed. Even if you present a subscriber JWT, the provider destination will be returned if present.
  • subscriberFirst: Tries to get from the subscriber first using the JWT. If no valid JWT is provided or the destination is not found, it tries the provider as described for AlwaysProvider.

The selection strategy can be passed as an optional argument to the execute() method. The default value is subscriberFirst. The selection strategies can be used to control for which account a destination lookup is attempted:

note

In principle, it is possible to define destinations not only on the account level but also on the destination service level. These destinations are called instance destinations since they are tied to a service binding called instance on SAP BTP. In every request, these destinations are added to the destinations returned by the destination service.

Destination Lookup Without a JSON Web Token

There are situations where you do not have a JWT issued by the XSUAA but need to look up a destination, e.g., in background processes. In such situations, the property iss of the DestinationAccessorOptions can be used:

MyRequest.execute({ destinationName: 'myDestination', iss: yourIssuerValue });

The value for iss is supposed to be the same as in a JWT issued from the XSUAA, e.g., https://yourSubdomain.localhost:8080/uaa/oauth/token. In principle, only the host of the URL is relevant, but since the same parsing and replacement methods are used for the JWT handling, the URL has to be provided in the format above.

danger

If a JWT is used in the destination lookup, a validation of the provided token is performed. This validation ensures that the JWT has not been manipulated. If only the iss is provided, no such validation is performed.

Note that the given subdomain value defines from which tenant destinations are fetched. A wrong value may break the isolation for tenants. It is your responsibility as a developer to ensure that the provided value for the iss property is valid.

Getting All Destinations

The SAP Cloud SDK supports getting all destinations only from the destination service. This is possible through the getAllDestinationsFromDestinationService() function. Based on the provided JWT, you will either receive all subscriber or provider destinations.

Example:

import { getAllDestinationsFromDestinationService } from '@sap-cloud-sdk/connectivity';

// Will attempt to get all provider destinations
getAllDestinationsFromDestinationService();

// Will attempt to get all subscriber destinations
getAllDestinationsFromDestinationService(subscriberJWT);

It is important to note that these destinations won't contain an authentication token. If you need the token, call the specific destination with getDestination({destinationName: yourDestination}).

Destination Fetch Options

The execute(), getDestination(), and executeHttpRequest() functions perform a destination lookup by name as discussed above. You can pass options to adjust how the destination is fetched. A few of the options were already listed above, but this section gives a comprehensive overview:

  • destinationName: The name of the destination to be fetched. This is the only mandatory property, all the other parameters are optional.
  • serviceBindingTransformFn: A custom transformation function to control how a Destination is built from the given Service.
  • jwt: The JSON Web Token. The property is mandatory in the following cases:
    • User-dependent authentication flow is used, e.g., OAuth2UserTokenExchange, OAuth2JWTBearer, OAuth2SAMLBearerAssertion, SAMLAssertion or PrincipalPropagation.
    • Multi-tenant scenarios with destinations maintained in the subscriber account. This case is implied if the selectionStrategy is set to alwaysSubscriber.
  • iss: Issuer URL which can be used to obtain destination for a subscriber tenant if no JWT is present. Read the detailed documentation above before using this option.
  • selectionStrategy: Specifies the order in which accounts are searched for a destination. Default is subscriberFirst. Alternative values are alwaysProvider and alwaysSubscriber.
  • iasToXsuaaTokenExchange: Switches on token exchange from IAS format tokens to XSUAA if needed using the @sap/xssec library. The default value is true.
  • cacheVerificationKeys: Switches on caching for the verification certificates for the JWT. The default value is true.
  • useCache: Switches on caching for destinations received from the destination service. The default value is false.
  • isolationStrategy: Specifies how the destination cache is scoped. The value is automatically set but under certain conditions you may want to optimize it.
  • enableCircuitBreaker: Switches on circuit breakers to protect the calls to the XSUAA and destination-service. The default value is true.
  • timeout: Sets the timeout for the calls to SAP BTP services like XSUAA and destination-service. The value is in milliseconds and the default value is 10000 (10 seconds). There is another timeout option on the request level, setting the timeout for the calls to the destination target.

Destination Properties

The destination object may contain additional properties. The properties change the behavior of how the SAP Cloud SDK handles the HTTP request at runtime.

SAP Client

The property sap-client is considered by the SAP Cloud SDK. When this property is set, it is used as the header parameter sap-client with the specified value in the HTTP request to the target system.

SAP client property on destination

Trust Configuration

By default, SAP BTP only trusts certain certificate authorities. If you want to make HTTPS requests against systems that use certificates from other certificate authorities, you can configure the following properties:

  1. TrustStoreLocation: The SAP Cloud SDK adds the provided certificate in the ca property of the node client.
  2. TrustAll: The SAP Cloud SDK adds the inverted value as the rejectUnauthorized

For additional information on trust configuration have a look at the more detailed guide.

danger

Please use the TrustAll with great caution since it opens the gate to man-in-the-middle attacks.

JWT Validation

If you use JWTs not issued by the XSUAA service, you can configure validation by the destination service using the x_user_token.jwks or x_user_token.jwks_uri property. For more details on JWTs, have a look at the more detailed guide.

caution

If you want to use a custom JWT in combination with the destination cache, the JWT must contain the properties zid and user_id. These properties are used to construct the cache key.

Additional Headers and Query Parameters on Destinations

The destination service has a convention to define static headers and query parameters on destinations. Create additional properties in your destination in the SAP BTP cockpit and define their values as follows:

  • URL.headers.HEADER_KEY for headers
  • URL.queries.QUERY_KEY for query parameters

Replace HEADER_KEY and QUERY_KEY with the name of the headers or query parameters and set the respective values.

Additional properties on destination

In the example above, the destination has an apiKey header with the value <my-api-key> and a language query parameter with the value EN.

The SAP Cloud SDK adds those additional headers and query parameters for every communication with the given destination.

Rules of Precedence

The SAP Cloud SDK adds headers and query parameters from different sources. Some sources take precedence over others (highest to lowest):

  1. custom: headers/query parameters added to a request directly
  2. additional properties: headers/query parameters defined on a destination
  3. internal: headers/query parameters built by the SAP Cloud SDK

Headers or query parameters built by the SAP Cloud SDK are overwritten by additional headers and query parameters on the destination. Custom headers and query parameters, however, overwrite the additional properties.

note

Header names keep their casing but overwrite other headers independent of the casing, e.g., AUTHORIZATION overwrites authorization. This does not apply to query parameter names`.