Using JSON Web Tokens (JWT)

Objective

After completing this lesson, you will be able to use JWT to securely transmit identity information between parties as a JSON object.

What is JWT?

The interconnected digital landscape your organization is operating in mandates the secure and trusted exchange of user identity information between the applications and services you’re using. You frequently need to share user data, such as login status or profile details, between client-side applications and backend systems, or between server side components.

JSON Web Tokens (JWT) offer a robust, standardized solution to protect against tampering and unauthorized access by enabling secure and efficient identity transfer within your SAP Customer Data Cloud environment.

JWTs help you safeguard sensitive user data and streamline authentication and authorization workflows.

What is a JSON Web Token (JWT)?

Header reading JSON Web Token, abbreviated as JWT or “jot”

A JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way to securely transmit information between parties using JSON objects. The information JWTs carry can be verified and trusted because it is digitally signed. This digital signature protects the token from tampering and ensures its authenticity.

JWTs can be signed using different cryptographic algorithms. Common methods include using a shared secret key with the HMAC (Hash-based Message Authentication Code) algorithm or employing a public/private key pair using RSA (Rivest–Shamir–Adleman) for asymmetric encryption. The choice of algorithm depends on the security requirements and the environment in which the JWT is used.

For more information, refer to the Introduction to JSON Web Tokens documentation.

Why use JSON Web Tokens?

The primary motivation for using JWTs revolves around enhancing security and efficiency in identity management. Here are key reasons and benefits:

  • Preventing Attacks – JWTs are designed to prevent man-in-the-middle attacks and data tampering. The digital signature ensures that once a token is issued, any alteration to its content will invalidate the signature, making the tampering detectable.
  • Customer Data Cloud Support – SAP Customer Data Cloud (CDC) supports the generation of JWTs, both on the client SDK and through its REST API. This integration allows for seamless incorporation of JWTs into your CDC-powered applications.
  • Client-Side Customization – Client-side JWTs can be requested after a user logs in, allowing for the inclusion of custom claims (additional fields and an expiration time). This flexibility is valuable for tailoring the token to specific application needs.
  • Integration and Efficiency – JWTs are lightweight, small, and quick to process, making them an excellent integration option for various systems. They are widely adopted by major platforms and devices, including Google apps, Amazon Alexa, and IoT devices, highlighting their versatility and reliability.
  • Avoiding Extra API Calls – By embedding relevant user information (claims) directly within the JWT, applications can avoid making additional calls to CDC to retrieve basic user details (like UID or profile fields). This reduces network overhead and improves performance.

JWT Use Example

SAP Customer Data cloud sends a JWT to the front end and a Public Certificate to a flash drive. Receiving a JWT from the font end, the flash drive can then generate Trusted Claims.

Call the accounts.getJWTPublicKey API with a site's API Key to retrieve a Public Certificate in JWK format. You can then use the same Public Key for signature validation.

You can also manually test whether a JWT is valid by using the Gigya id_token Validator

The Structure of a JSON Web Token

Encoded JWT Format

Tripartite string in the format: header.payload.signature, encoded in base64.

In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are typically Base64 URL encoded:

You can go to the JSON Web Token (JWT) Debugger, paste the encoded version, and get the decoded version as a response.

Decoded JWT Format

Example of the decoded JWT. The header shows the type (JWT), algorithm (RS256), and keyid. The payload fields ISSuer, AUDience, EXPiration time, Issued AT time, and SUBject are emphasized. The Signature shows the fields used to sign the JWT.

Here is what the decoded version reveals:

  • Header – The header typically contains three fields:
    • typ – The token type, which is always JWT
    • alg – The signing algorithm used, such as HMAC SHA256 or RSA. You need to know the algorithm used to create and verify the token’s signature.
    • keyid – The key’s id.
  • Payload – The second part of the token contains the claims. Claims are statements about tan entity (typically the user) and additional data. Claims can include:
    • Registered Claims – Predefined claims like iss (issuer), exp (expiration time), sub (subject, often the user ID), and aud (audience).
    • Public Claims – Custom claims agreed to by parties using these JWTs. To avoid collisions, these claims should be registered in the IANA JSON Web Token Registry or be defined as a URI that contains a collision-resistant namespace.
    • Private Claims – Custom claims created to share information between parties that agree on their use.
  • Signature – A critical security feature used to verify that the message hasn’t been altered at any point during transmission. If the token is signed with a private key, you can also verify that the JWT’s sender is who they claim to be.

The signature is created by using the algorithm specified in the header to sign the combination of the encoded header, the encoded payload, and either a secret or a private key.

For more information, refer to the OpenID Connect Op Setup documentation in the SAP Help Portal to decode response.

JWT API

JWTs can be generated an used in both client-side (front-end) and server-side contexts in SAP Customer Data Cloud.

Client-Side (Front-End) Usage

The Front End asks Customer Data Cloud, as a RaaS, to show the login screen-set. Based on its workflow policies and email templates, CDC triggers an onLogin event and writes a User Object (UID) as a cookie in the front end, which calls Get JWT. That method communicates with Identity Management on the CDC end, which uses Native Login. A validated and sharable JWT is sent to the Backend or third party system, which calls getJWTPublicKey from Identity Management on CDC.

This scenario is common when a user interacts directly with a client application (e.g., a web browser or mobile app). In this use case, we want access to a JWT, specifically to its payload, to retrieve trusted content (several user info fields for the currently logged-in user from a backend or third-party system).

Flow Steps:

  1. User Login – SAP Customer Data Cloud presents the login screen-set (such as email/password or social login), and the user authenticates with the CDC Identity Manager using the current Customer Identity policies and setup.
  2. onLogin Event – After successful authentication, the client-side onLogin event is triggered . A User Object containing the User ID (UID) is returned and typically stored in a cookie.

    Note

    For more information, see Advanced Cookie Reference on the SAP Help Portal.
  3. Retrieve JWT – The client application uses the Web SDK (Client API) to retrieve a JWT from the Identity Manager. A common API call is gigya.accounts,getJWT.
  4. JWT Validation – The retrieved JWT must be validated using the public key obtained from the server via a REST API method (accounts.getJWTPublicKey).

Public keys are often cached and should be periodically checked for validity using the keyid field, as they can change for security reasons.

For more information, see How often CDC refreshes the JWT public key on SAP for Me.

Sample Business Scenarios

  • Preventing UID Tampering – When a user logs in on the front-end, for instance with email/password with SAP Customer Data Cloud screen-sets or social login, their UID must be to a server for authentication and further processing (e.g., adding to a database, creating a server-side session). To avoid the UID being tampered with on its way to the server, it can be wrapped in a JWT generated client-side. The JWT’s signature ensures the message was not altered during transmission.
  • Authorizing Against Protected Resources – A client-side generated JWT can contain custom claims, such as data.membershipType. This claim can then be used to authorize access to specific resources (for instance, limiting specific video content to ‘premium’ users).
  • Sharing Profile Information – JWTs can serve as a simple mechanism to transmit or exchange profile data. For instance, when redirecting a user to an external website to fill out a form, a JWT containing their first name, last name, and email can be sent. The target website can then retrieve this information from the JWT to auto-populate the form or even authenticate the user.

Client Side JWT API Call Example (Web SDK)

JavaScript
1234
// JavaScript Code Example gigya.accounts.getJWT({fields:’profile.firstName,profile.lastName’,expiration:60})

This API obtains an id_token containing the active session's user data. Its key parameters include:

  • fields – A comma-separated list of fields from the user's Profile or Data objects to include in the JWT. By default, only the user's UID is returned.
  • expiration – The time the JWT will be valid, in seconds, from the time of the request; the default is 300.
  • audience – Adds the aud claim to JWT tokens returned. This claim specifies which audience(s) the token is valid for. If a service receives the token but is not in the audience list, the service should reject the token.
  • callback – A reference to a JavaScript callback function.

For more information on JSON web tokens, see the Configuring JSON Web Token (JWT) in SAP Customer Data Cloud video.

For more details on these parameters see the accounts.getJWT JS documentation on the SAP Help Portal.

Server-Side Usage

Consider a use-case where we want access to a JWT’s payload to retrieve trusted content: several user info fields for logged-in users from a backend or third-party system.

The Front End asks Customer Data Cloud, as a RaaS, to show the login screen-set. Based on its workflow policies and email templates, CDC triggers an onLogin event and writes a User Object (UID) as a cookie in the front end. That UID is sent as the Server-side UID on the backend or third-part, which validates the UID with CDC's Itdentity Management. This validated UID is used to obtain a sharable JWT Token from Identity Management by calling getJWT, and the JWT is shared with the third-party, which compares it with the public key obtained from Identity Management.

Flow Steps:

  1. User Login & onLogin Event – After SAP Customer Data Cloud presents the login screen set, the user logs in, triggering the onLogin client-side event. The UID is returned, and stored in a cookie. This step is the same as for the front-end (client side) scenario.
  2. UID Validation – For any user authenticated user, the server-side application validates the UID using a server-side SDK or the REST API.

    For example,

    • call SigUtils.validateUserSignature in a server SDK
    • call the REST method accounts.getJWT, then check the UID, signatureTimeStamp, and UIDSignature fields of the returned User JS object using the signature validation process (described in Security Best Practices).
  3. After validating the UID on the server side, use the Rest API or any server-side SDK to retrieve a JWT (JSON Web Token) from the Identity Manager.
  4. JWT Validation – Validate the retrieved JWT using a public key obtained from the server via the REST API and accessible to the back-end application. Similar to the client-side,these public keys are cached and require periodic validation using the keyid field.

Sample Business Scenarios

  1. Server-to-Server Federation – An e-commerce backend, following a user log in, might need to redirect the user to a partner payment system. The e-commerce backend can request a user's JWT from SAP CDC via a REST API call (passing the UID in a signed request). This JWT is then transmitted to the partner payment system for validation and authentication.
  2. User impersonation – A system might allow a user (User 1) to approve leave requests on behalf of another user (User 2). The server-side system can ask SAP CDC to generate a JWT for User 2, which can then be used as an impersonation mechanism, allowing User 1 to perform tasks on another system as User 2.
  3. IoT and device registration – To associate an identity with a device (such as a car or smartwatch), a user might find it easier to log in/register on a secondary device, such as a mobile phone, tablet, or laptop. A server-side generated JWT, linked to the user, can then be retrieved by the IoT device (after validating a PIN or QR code). This JWT then acts as an access token to provide direct access to accounts for reads / writes.

Server-Side JWT API Call Example (REST API)

JavaScript
1234567891011
final String apiKey = "PUT-YOUR-APIKEY-HERE"; final String secretKey = "PUT-YOUR-SECRET-KEY-HERE"; String apiMethod = "accounts.getJWT"; GSRequest request = new GSRequest(apiKey, secretKey, apiMethod); Rewuest.setParam("targetUID", "Enter-A-Valid-UID-Here"); GSResponse response = request.send

This API obtains an id_token containing an existing user's data in JWS format.

The parameters for accounts.<Data_Center>/accounts.getJWT are:

  • apiKey – The API key of the target site containing the existing user's data.
  • audience – Used to add the aud claim to JWT tokens returned. The aud claim tells the receivers of a JWT token which audience(s) the token is valid for. If a service receives the token but is not in the audience list, the service should reject the token.
  • targetUID – The UID of the user whose data is being requested.
  • userKey – The userKey associated with the secret.
  • secret – An application/user key and its corresponding secret.
  • fields – Any existing profile and data fields in the target site's database you want to return in the JWT for this specific targetUID.
  • expiration – The TTL of the returned JWT in seconds. If this parameter is not passed, the default is 300.

For more info on these parameters, see accounts.getJWT REST on the SAP Help Portal.

Note

<Data_Center> can be:

  • us1.gigya.com - For the US data center.
  • eu1.gigya.com - For the European data center.
  • au1.gigya.com - For the Australian data center.
  • eu2.gigya.com - For the Russian data center.
  • cn1.sapcdm.cn - For the Chinese data center.
  • global.gigya.com - For Global site groups.

Demonstration

In the following demonstration, we see how to retrieve an ID Token in SAP Customer Data Cloud:

JWT Validation

Validating a JWT is crucial to ensure its authenticity and integrity.

Screenshot of the Provider Endpoints dialog emphasizing the 'n' and 'kid' fields in the JSON Web Keys text box.

The screenshot above show the Provider Endpoints, accessible through a link on the Customer Data Cloud console > Identity > Connect > Inbound Federation > OIDC > OPs page.

To get the valid public key for the originating site:

  • If you use accounts.getJWT, call accounts.getJWTPublicKey with that site's API key.
  • If you use OIDC, pick up the key from OIDC OP's Metadata Configuration in the Console.

For more information refer to the Validate a JWT from SAP Customer Data Cloud documentation in the SAP Help Portal.

Obtaining the Public Key

JSON returned by a call to accounts.getJWTPublicKey, emphasizing the value of the 'n' field, identified as the Modulus, a base64url encoding of the returned id-token, and the 'e' field, identified as the exponent value for the RSA public key, base64url encoded.

Public keys are subject to change without warning for security reasons. The recommended best practice is to check the kid returned in the JWT header against the kid (Key ID) of the public key returned by accounts.getJWTPublicKey, or that you received from the OP; if they do not match, you must update your public key using accounts.getJWTPublicKey or by contacting the OP.

For more information refer to the accounts.getJWTPublicKey REST documentation in the SAP Help Portal.

Steps to Validate a JWT from SAP Customer Data Cloud

Three steps identified: Receive JWT, Split JWT into three parts, and Validate the id_token.

The id_token returned from SAP Customer Data Cloud is a JWT that consists of 3 parts. To validate the authenticity of the JWT, you must compare the header + payload (parts 1 and 2) against the signature (part 3) using the originating site's public key (the site that contains the user whose data you are attempting to validate).

Step 1: Receive JWT from Either

  • accounts.getJWT API/SDK call
  • Customer Data Cloud OIDC OP's public key
  • Webhooks 2.0 notification (in the x-gigya-sig-jwt header)

Step 2: Split JWT into three parts. The JWT id_token consists of three parts: header, payload, and signature.

Demonstration – Putting It All Together

While an ID Token is used to verify the user's identity (identification), a Bearer Token is used to verify what resources the user has access to (authorization). Let's demonstrate how that's done:

Summary

In this lesson, you have learned that:

  • JSON Web Tokens (JWT) are an open standard for securely transmitting digitally signed identity information as a compact, self-contained JSON object.
  • JWTs prevent tampering and man-in-the-middle attacks by digitally signing the token, ensuring trust and integrity of the transmitted data.
  • A JWT comprises three Base64Url encoded parts: a Header (type and algorithm), a Payload (claims about the entity), and a Signature (for verification).
  • SAP Customer Data Cloud supports both client-side and server-side JWT usage, enabling secure identity transmission for front-end applications, server-to-server communication, and device registration.
  • JWT validation involves splitting the token, retrieving the appropriate public key, and comparing the header and payload against the signature to confirm authenticity and integrity.