Technical Articles
Deep Dive 8 with SAP Cloud SDK: Leverage Principal Propagation via OAuth 2 when consuming a Business API from S/4HANA Cloud
In June 2020 we have launched a brand new documentation portal which consolidates all the knowledge, feature documentation, comprehensive guides, video tutorials, troubleshooting, release notes, API documentation and more. Please, use it as a single reference point about SAP Cloud SDK. From now on it’s the most complete and up to date source of information about the product.
Disclaimer: This blog post is only applicable for the SAP Cloud SDK version of at most 2.19.2. We plan to continuously migrate these blog posts into our List of Tutorials. Feel free to check out our updated Tutorials on the SAP Cloud SDK.
The following steps will explain how to leverage principal propagation via OAuth 2 to consume a business API exposed in S/4HANA Cloud and consumed within a cloud app running in the SAP Cloud Platform. This means logging on to S/4HANA Cloud as an existing physical person, opposed to connecting via a technical user.
If you want to follow this tutorial, we highly recommend checking out the previous parts of this series, especially the deep dive about Communication Management and Identity & Access Management.
Note:
- This post is part of a series. For a complete overview visit the SAP Cloud SDK Overview.
- This tutorial requires access to an SAP ERP system,
- This tutorial requires access to an SAP Cloud Identity tenant.
- So far, this tutorial focuses on the Neo runtime on SAP Cloud Platform.
Goal of this blog post
In this blog post we will start to make the distinction between business users and technical users to motivate the need for principal propagation. Having understood the requirement to log on as a business user, we will explain the theory behind the OAuth 2 protocol which is used in the context of S/4HANA Cloud to achieve principal propagation.
Leaving the theoretical background behind us we then proceed with demonstrating how the connection from our cloud app to S/4HANA Cloud app via OAuth 2 can be setup.
Concluding we will then connect the sample app from the first deep dive to proof that the authentication via OAuth 2 worked.
The idea of Principal Propagation: Business User vs. Technical User
Generally, we need to log on to S/4HANA Cloud in order to authenticate and thereby later on allow S/4HANA Cloud to check that we are authorized to conduct the activity in mind, such as displaying product master data. We can log on to S/4HANA Cloud either as business user or technical user.
The following table outlines the main differentiating factors between business and technical users in the context of S/4HANA Cloud:
Business User | Technical User | |
Identity Representation | commonly an existing physical person using S/4HANA Cloud | commonly other software/technical systems |
Purpose and Usage | involves user interface interaction in Fiori | involves no user interface, commonly API calls (e.g. OData) |
Authorization Management | receives authorizations by business role assignment, authorizations restrictable in Fiori app | authorizations for services inside communication scenario, authorizations not adjustable |
Authentication Method | OAuth 2 SAML Bearer Assertion Flow | Basic Authentication (i.e. username and password) |
User Creation | Check out Fiori app “Maintain Business User” | Check out Fiori app “Maintain Communication Users” |
Synonyms | not applicable | Also referred to as Communication User |
Based on the given information you may decide for your use case whether you utilize a business or a technical user.
Consider the following example: Imagine a cloud app that enables your employees to manage product master data. Managing could mean, for instance, to ensure that the master data look right. Furthermore, it makes sense that not every employee of this cloud app is authorized to see all products in your S/4HANA Cloud system, but rather those ones he is responsible for.
The given example is a perfect case for utilizing business users because you would not be able to specify user-specific authorizations when using a technical user.
Technically, your business users log on to the cloud app in the web browser with their credentials or a certificate. Let’s assume that they are identified by e-mail address. Once your cloud app invokes the product master API inside S/4HANA Cloud, the identity (also referred to as ‘principal’) of the currently logged on user is forwarded to S/4HANA Cloud. As S/4HANA Cloud trusts your cloud app (in simple words) you are automatically logged on to S/4HANA Cloud. We call this process Principal Propagation because your principal is propagated throughout multiple systems.
In the context of S/4HANA Cloud we use OAuth 2 as protocol to achieve Principal Propagation. Therefore, we will dive into some theory about OAuth 2 in the next section.
Some theory: How OAuth 2 works under the hood
OAuth 2 is the industry standard for managing authorizations and used by a majority of established internet applications and services. Let us clarify some terms beforehand.
The resource owner is the user who owns one or multiple resources. Resources are protected by scopes. For instance, to keep it simple we can say that one scope corresponds to one resource.
The OAuth client has a unique ID (so-called client ID) and is the application that seeks access to one resource owned by the user and hosted by the resource server (also referred to as service provider). The authorization server (also referred to as identity provider) is the component that validates authorization requests. The OAuth 2 protocol distinguishes different flows for different purposes.
There is the authorization code flow which you might know from popular internet-based mailing services or social networks.
Leveraging this flow you are able to use your credentials of e.g. your social network account to log on to another application. In this example the social network acts as authorization server. The target application/client redirects you to the social network (in particular: to the authorize endpoint) where it presents you the log on screen you are familiar with. After entering your credentials the authorization server issues the authorization code and redirects you back to the client. Subsequently, the client posts the authorization code (and few other information in addition) to the authorization server (in particular: to the token endpoint) which in turn issues an access token after the authorization code was validated. Furthermore, the client uses the access token for all subsequent calls to the resource server for the purpose of authentication.
Apart from that there is the SAML bearer assertion flow (also check out the respective SAP help page) which makes use of SAML assertions instead of the authorization code.
In contrast to the previous flow we omit the first step where the user entered his credentials. Instead the SAML 2.0 identity server issues a SAML assertion which contains amongst others the user identifier within the client application. Additionally the SAML assertion contains its digital signature. The client sends this SAML assertion to the authorization server (in particular: to the token endpoint) which in turn issues the access token after validating the SAML assertion. Validation includes here amongst others to verify the digital signature. As a consequence we need a trust relationship between the authorization server and the SAML 2.0 Identity Provider.
Let us illustrate above theory in the context of an example communication flow between SAP Cloud Platform and S/4HANA Cloud in the next section.
Example flow: How OAuth 2 works connecting SAP Cloud Platform and S/4HANA Cloud
Let us come back to the use case we illustrated above: We have a cloud app that enables our employees to manage product master data. When one user launches the app, the app obtains a list of product master data from S/4HANA Cloud by an OData call.
During the product master retrieval, the following components are involved:
- SAP Cloud Identity Tenant
- SAP Cloud Platform Local Service Provider
- SAP Cloud Platform Destination Service
- SAP Cloud Platform Application for Product Master Maintenance (the “cloud app”)
- S/4HANA Cloud Token Endpoint
- S/4HANA Cloud Product Master OData API
Recapping the OAuth 2 theory from above, the involved components map as follows to the OAuth 2 terms:
Involved component | OAuth 2 term |
SAP Cloud Identity Tenant | SAML 2 Identity Provider |
SAP Cloud Platform Local Service Provider | belongs to OAuth 2 Client |
SAP Cloud Platform Destination Service | belongs to OAuth 2 Client |
Cloud App | belongs to OAuth 2 Client |
S/4HANA Cloud Token Endpoint | Identity Provider/Authorization Server |
S/4HANA Cloud Product Master OData API | Service Provider/Resource Server |
Once your cloud app is about to generate the OData request, it utilizes an HTTP destination that uses the authentication method OAuth2SAMLBearerAssertion. This HTTP destination is configured inside the SAP Cloud Platform consumer account. The destination service on SAP Cloud Platform resolves this destination and notices that OAuth 2 SAML Bearer Assertion flow should be used.
For this purpose the local service provider of your SAP Cloud Platform account issues a SAML assertion whereas it considers the identity of the currently logged on user. This identity was formerly retrieved from the SAP Cloud Platform Identity tenant that is connected to the respective SAP Cloud Platform consumer account.
Assume that John Smith has launched the cloud app, then (depending on the configuration) for instance the mail address john.smith@example.com is put into the field “name id” of the SAML assertion. Once the assertion is generated, the local service provider signs it by its private key.
The destination service then sends one HTTP POST request to the token endpoint of the S/4HANA Cloud system whose host name is specified inside the HTTP destination. In this step we authenticate at the token endpoint using the communication user credentials (i.e. user name and password). This requests contains amongst others the SAML assertion as base64 encoded string along with the OAuth 2 scope which corresponds to the target service in your S/4HANA Cloud system.
Once the token endpoint has received the request, it firstly validates the authenticity and integrity of the SAML assertion by verifying the digital signature. This assumes that the S/4HANA Cloud system trusts the local service provider. This trust relationship is established by providing the certificate of the local service provider to S/4HANA cloud during the configuration. Once the SAML assertion is considered authentic and integer, the contained name id value is extracted.
Subsequently the token endpoint searches for a business user in the system that has the e-mail address john.smith@example.com. If it is found, it conducts few more checks including business authorizations. If all checks are considered OK, then the token endpoint sends an HTTP response containing the OAuth access token.
Considering the OAuth access token the destination service then sends a second HTTP request to the product master API and passes the access token in the authorization header. Retrieving the access token the S/4HANA Cloud system knows which business user it belongs to and invokes the product master API.
Setting up the connection to S/4HANA Cloud via OAuth 2
Defining the status quo
Before we dive into to connection setup for OAuth 2, let us define from where we start. As origin point we assume that we have a deployed app on the Neo runtime in SAP Cloud Platform as indicated in step 2 of this blog series.
This app shall query the product master API via basic authentication. For this purpose you have to use the method implementation of doGet as follows:
@Override
protected void doGet( final HttpServletRequest request, final HttpServletResponse response )
throws ServletException, IOException
{
final PrintWriter writer = response.getWriter();
try {
final List<Product> productList = new DefaultProductMasterService().getAllProduct().top(100).execute();
writer.write(new Gson().toJson(productList));
response.setContentType("application/json");
} catch (Exception e) {
writer.write("Error: " + e.getMessage());
e.printStackTrace(writer);
}
}
We deployed this app to the Neo runtime and configure our destination to use basic authentication.
When launching the app under relative path /hello we do see the JSON output containing the product master data retrieved from the S/4HANA Cloud system the destination points to.
Subsequently we will conduct the necessary steps to authenticate to S/4HANA Cloud via OAuth 2.
Customize SAP Cloud Platform Local Service Provider
The first step is to establish the trust relationship between the SAP Cloud Platform local service provider and the SAP Cloud Identity tenant.
For this purpose, we navigate to Security –> Trust within our SAP Cloud Platform account and set the local service provider settings to Custom.
In addition we click on Generate Key Pair to get a fresh pair of private and public key. You can leave the local provider name as defaulted or change it to your needs (which we did here for demo purposes).
Afterwards we download the metadata file of our local service provider using the link Get Metadata.
Register SAP Cloud Identity Tenant in Local Service Provider
Log on to your SAP Cloud Identity tenant and navigate to Applications & Resouces –> Tenant Settings. This page shows the signing certificate of this tenant. Download its metadata.xml by using the link at the bottom of the page.
Going back to the SAP Cloud Platform account, we open the tab Application Identity Provider under Security –> Trust.
After clicking on Add Trusted Identity Provider we browse to the metadata.xml of the SAP Cloud Identity tenant we downloaded previously. Open the tab Attributes and under Assertion-Based Attributes maintain both a star (“*”) for Assertion Attribute and Principal Attribute.
By clicking Save we confirm this dialog.
Now you do see your SAP Cloud Identity tenant as application identity provider in your SAP Cloud Platform account. Make sure that it is marked as the default one.
Register Local Service Provider in SAP Cloud Identity Tenant
Since the trust relationship is bidirectional, we have to supply the metadata of our SAP Cloud Platform account to the SAP Cloud Identity tenant also.
For this purpose we log on to the SAP Cloud Identity tenant and navigate to Applications & Resources –> Applications. Here we add another entry by clicking on Add. The appearing dialog asks for a name. Since this entry corresponds to your SAP Cloud Platform account, you should choose a meaningful name which expresses this notion.
The SAML 2.0 configuration of this entry is still missing as you can see in the following screenshot.
When you click on SAML 2.0 Configuration you can upload the metadata file of the SAP Cloud Platform account you downloaded in the beginning.
Click Save the trust relationship is established.
Download Signing Certificate from SAP Cloud Platform Account
The SAML assertion sent to S/4HANA is signed using the private key of the local service provider. In order to enable S/4HANA Cloud to verify this signature it does need the corresponding certificate.
For this purpose we download the signing certificate of the SAP Cloud Platform account.
Navigate to Security –> Trust and copy the content of the text area next to Signing Certificate.
Afterwards open up a text editor on your machine and paste the certificate there. Now put the certificate string (in fact it is base64 encoded) between the two lines below.
-----BEGIN CERTIFICATE-----
your certificate goes here
-----END CERTIFICATE-----
Give this file a name that ends on “cer” and save it on your machine,
Create Communication Arrangement in S/4HANA Cloud
Create Communication User
Subsequently we will create the communication arrangement and related entities inside S/4HANA Cloud.
Firstly, let us create a new communication user inside the Fiori app Maintain Communication Users.
We need this communication user to utilize its credentials when accessing the token endpoint in S/4HANA Cloud aiming to retrieve an OAuth 2 access token.
Create a new communication user and give it an appropriate name. Remember the user name and the password. You will need it later. In this example we use the name MARCOS_PM_COMM_USER.
In this deep dive we focus on the inbound communication from the S/4HANA Cloud perspective, i.e. our cloud app calls S/4HANA Cloud, but the latter one does not call into our cloud app. However, the communication scenario SAP_COM_0009 for product master integration contains both inbound and outbound services and therefore we need to create an additional communication user for outbound purposes. As a consequence, you have to create another communication user. In this example we use the name MARCOS_BP_OUTBOUND_USER.
Create Communication System
We can continue by creating a communication system which represents your SAP Cloud Platform account.
Open the Fiori app Communication Systems and click on New.
Enter an approriate system ID, system name, host name and logical system.
Further down under OAuth 2.0 Identity Provider we have to activate the checkbox named Enabled and can then upload the signing certificate we downloaded previously. In addition we have to supply the provider name where we enter the name of the local service provider. You can obtain this information from your SAP Cloud Platform account under Security –> Trust (look for Local Provider Name).
Below we have to choose the previously created communication users.
Save this communication system and note down its name.
Create Communication Arrangement
Now we can continue and create the communication arrangement.
Open the Fiori app Communication Arrangements and click New.
Choose communication scenario SAP_COM_0008 and give your communication arrangement a proper name.
Choose the communication system and communication user we created beforehand.
For inbound communication make sure that you choose the communication user along with the authentication method OAuth 2.0.
For outbound communication choose the second communication user from above.
As we omit the outbound communication in this deep dive, we have to deactivate all services under Outbound Services. For this purpose you have to uncheck the Service Status for each particular service.
Click Save and your communication arrangement gets activated.
Maintain HTTP Destination in SAP Cloud Platform Account
In this step we will adjust the HTTP destination in our SAP Cloud Platform account. As of now it uses basic authentication. Our aim is to adapt it to use OAuth 2.
In the end your destination must look similar to the following:
At first we change the authentication to OAuth2SAMLBearerAssertion which will show more input fields than before.
Specify the remaining fields as follows:
Field | Explanation | Value |
Name | The SAP Cloud SDK considers the destination having name ErpQueryEndpoint as the default one for HTTP-based communication. | ErpQueryEndpoint |
Type | Specifies the communication protocol. | HTTP |
Description | Provide a meaningful description about the purpose of this destination. | Connection to my S/4HANA system |
URL | Specifies the URL of the target S/4HANA Cloud system. Only provide the protocol, the host name and the port, i.e. no relative path. | https://<my_host_name>.com |
Proxy Type | Specifies whether the communication is a direct HTTP call or tunneled via the SAP Cloud Connector. | Internet |
Authentication | Specifies which authentication method is used | OAuth2SAMLBearerAssertion |
Audience | Specifies the target audience of the issued SAML assertion. Use the host name of your S/4HANA Cloud system. | https://<my_host_name>.com |
Client Key | Represents the OAuth client registered in the S/4HANA Cloud System. | Use the name of your inbound communication user. Note: Use the name you specified, not the generated name like CC……… |
Token Service URL | Specifies the URL of the token endpoint, i.e. the HTTP endpoint where the SAML assertion is sent to. | https://<my_host_name>.com/sap/bc/sec/oauth2/token |
Token Service User | Specifies the user name for authentication to the token endpoint. | Use the name of your inbound communication user. Note: Use the name you specified, not the generated name like CC……… |
Token Service Password | Specifies the password for authentication to the token endpoint. | Use the password of your inbound communication. |
Additional Parameters:
Parameter | Explanation | Value |
authnContextClassRef | Specifies the requested authentication context. | urn:oasis:names:tc:SAML:2.0:ac:classes:X509 |
scope | Specifies the OAuth scope of the OData service you want to invoke. | API_PRODUCT_SRV_0001 |
nameIdFormat | Specifies which format your principal sent to S/4HANA Cloud has | urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress |
userIdSource | Specifies which attribute of your SAP Cloud Identity user master data is propogated as principal to S/4HANA Cloud |
Maintain Business User in S/4HANA Cloud and SAP Cloud Identity
The principal propagation relies on the equivalence of user master data attributes in both S/4HANA Cloud and the SAP Cloud Identity. In the following we will create user master data for the business user and configure which user master data attribute is considered to be common.
Maintain Business User in S/4HANA Cloud
Open the Fiori app Maintain Business Users from the Fiori launchpad.
Click on New, choose one from the existing employees and enter a business user similar to the example user shown in this screenshot.
Ensure that the e-mail address is maintained. If you cannot find an employee with an e-mail address, you can maintain a new employee in the Fiori app Maintain Employees.
In addition you have to assign the shown business role. This role assignment ensure that this business user can invoke the product master API.
Maintain Business User in SAP Cloud Identity
Log on to your SAP Cloud Identity tenant and navigate to Users & Authorization –> User Management. Click on Add User and create another user by assigning the same mail address as specified for the business user previously created inside S/4HANA Cloud. Specify a password and make sure to remember it.
Connect our sample app to S/4HANA Cloud as Business User
Open your cloud app under the relative path /hello. Now you can see the log in form of your SAP Cloud Identity tenant.
By entering the mail address of your SAP Cloud Identity user and its password, you are logging on as this user to your app. When the cloud app conducts the OAuth 2 SAML Bearer Assertion flow with S/4HANA Cloud, the SAML assertion sent to the token endpoint contains the mail address of this user. S/4HANA Cloud finds your business user by this mail address and checks if he is allowed to invoke the called OData API. As we assigned the business role Master Data Specialist for Product Data, this authorization is granted. As a consequence, the cloud app prints the returned product master data as JSON.
Conclusion
Within this deep dive we have introduced the distinction between business and technical users along with the purposes and trade-offs of each. Based on the given example cloud app we decided that a business user is the best choice. After explaining the theoretical concept of OAuth 2 we presented its application in the context of SAP Cloud Platform and S/4HANA Cloud in conjunction with the entire configuration steps. The cloud app example in this deep dive uses the virtual data model for OData.
Stay tuned for upcoming blog posts about the SAP Cloud SDK.
Hi Marco Dahms,
Very informative blog. Thank you. really helps.
Do we have any documentation for achieving the Principal propagation for on-premise systems?
Or what steps will be different for on-premise version?
Thank you in advance,
Best Regards,
Venu
Dear Venu,
check out the following documentation:
Also I may point you to the book Extending SAP S/4HANA which covers the principal propagation towards on-premise systems as well.
Thank you and kind regards
Marco Dahms
This deep dive focuses on the Neo environment on SAP Cloud Platform.
If you conduct the same on Cloud Foundry, pls use the destination property userIdSource = email instead of mail.
Hi Marco Dahms ,
great blog! really helps to understand the flow.
I get an error when calling my s4/hana cloud api from my java app:
Checking default traces for the app, I see the following error: “invalid_scope”
My communication arrangement in s4hc looks like this:
and my destination in scp neo:
additional properties:
Do you have any suggestions how to solve the error?
Do you consider it can be related with the definition of the communication system in s4hc? It’s not clear for me what to set in host name and logical system fields.
Best Regards,
Marc
Dear Marc,
make sure that the business user in SAP S/4HANA that you want to invoke the API with possesses the authorization object S_SCOPE with the correct OAuth scope which corresponds to the used API.
Kind regards
Marco
Hello Marco,
->we are calling destination "ErpQueryEndpoint" using destination service API(Cloud Foundry) on SAP API HUB
->getting an error as displayed in the attachment.
->we are not deploying any app over BTP
->how do we pass an email to userIdsource. can we pass it directly to the HTTP destination on BTP?
-> could you provide a format of the hostname in s4hanacloud and what should be a logical system. we are currently using LocalHost as a hostname.
Also please help us to remediate the error.
Regards
AJ
Hi AJ,
I assume, as you asked the question here, that you are using a pretty outdated version of the SDK.
So the highest chance of fixing any issues would be to update to the latest version, which is 3.54.0 at this moment.
If the issue still persists you can open an issue in our public github repository here: https://github.com/SAP/cloud-sdk/issues
Greetings
Chris