We’ve migrated our documentation to a new site, which means some URLs have changed.
Subscriptions

Identity Linking: Implementation Checklist

1. Introduction

Implementing Identity Management Identity Linking involves integrating your external authentication system with Piano, configuring necessary settings, and ensuring that token handling and user data synchronization function as intended. This guide will walk you through the essential steps, including preparing your environment, configuring JWT tokens, setting up Identity Linking in the Piano dashboard, and handling authentication flows on your website. For a more general overview of Identity Linking, please refer to this documentation.

2. Prepare Your Environment

2.1 Access and Technical Requirements

  • Administrative Access:

    • Ensure you have administrator access to the Piano dashboard.

    • Obtain necessary credentials (Client ID and Shared Secret) from your external authentication provider.

  • Technical Requirements:

    • Your external authentication system must be capable of generating JWT tokens in compliance with JWT standards.

    • Familiarity with JWT token structure, claims, and signing algorithms (e.g., HS256, RS256).

    • Access to your website's codebase to implement JavaScript snippets and event handlers.

2.2 Understanding Identity Linking Capabilities

  • Identity Linking connects third-party authentication systems by ingesting JWT tokens.

  • Enables user tracking within Piano and access to Identity Management features while maintaining your existing authentication system.

  • Certain Identity Management features (e.g., password reset, social login) are not available through Identity Linking.

3. Prepare JWT Tokens

3.1 Include Required Claims

Ensure your JWT tokens include the following standard claims:

Required JWT Claims:

Claim

Description

Example Value

aud

Audience. Matches the Client ID in Piano.

"your-client-id"

iss

Issuer. Matches the ISS configured in Piano.

"https://your-domain.com"

sub

Subject. Unique identifier for the user (UID).

"user-unique-id"

exp

Expiration time. UNIX timestamp when the token expires.

1627667765

jti

JWT ID. Unique identifier for the token.

"unique-token-id"

email

User's email address.

"user@example.com"

first_name*

User's first name.

"John"

last_name*

User's last name.

"Doe"

* If these fields may be empty, include them with empty strings to allow for profile updates.

3.2 Include Custom Claims (Optional)

Add any additional user information as custom claims to pass metadata to Piano.

In Piano terminology, custom claims in the JWT are known as custom fields. Custom fields allow you to collect additional user data for first-party data collection and can be used within Piano forms and experiences. For more information, refer to the Custom Fields in Identity Management documentation.

Example Custom Claims:

  • newsletter: JSON list of newsletter IDs.

  • subscriptionLevel: Indicates user's subscription tier ("basic", "premium", "VIP", etc.).

  • preferredLanguage: Specifies user's preferred language ("en", "es", "fr", etc.).

  • purchaseDate: Date of last purchase.

Formatting Custom Fields:

  • Single-select List Type:

"custom_field_name": "[\"value\"]"
  • Multiple-select List Type:

"custom_field_name": "[\"value1\",\"value2\"]"

Ensure the values passed match the items defined in the custom field lists in Identity Management. Custom fields can be configured in the Piano dashboard and are used in forms for first-party data collection. For more details, see the Custom Fields in Identity Management documentation and Forms in Identity Management documentation.

By including custom claims (custom fields) in your JWT tokens and mapping them in Identity Linking, you enable seamless integration between your authentication system and Piano, allowing for enhanced user experiences and first-party data collection through Piano forms and experiences.

3.3 Token Signing and Security

Choose the Appropriate Signing Algorithm:

Identity Linking supports multiple signing algorithms. The most commonly used signing algorithms are:

  • HS256 (Symmetric):

    • Use a shared secret (must be at least 32 characters).

    • Base64-encode the shared secret before entering it in Piano.

  • RS256 (Asymmetric):

    • Use your RSA private key to sign tokens.

    • Provide the RSA public key (in plain text) to Piano during configuration.

You can find the full list of supported signing algorithms in the Identity Management Identity Linking documentation.

Important Notes:

  • Ensure the token is properly signed using the algorithm specified.

  • For JWE (encrypted tokens), the shared secret is used for decryption.

  • JWKS endpoints are not available; keys must be manually configured.

4. Configure Identity Linking in Piano Dashboard

4.1 Access Identity Linking Settings

  • Log in to your Piano dashboard.

  • Navigate to Edit Business, then select the User Provider tab.

  • Click on the Pencil Icon to edit your Identity Linking configuration.

4.2 External Identity Provider Configuration

  • Client ID:

    • Enter the aud claim value from your JWT tokens.

  • Shared Secret:

    • Enter the base64-encoded shared secret (for HS256) or public key (for RS256).

  • JWT Algorithm:

    • Select the algorithm used for signing your tokens (e.g., HS256, RS256).

  • External Identity Provider ISS:

    • Enter the iss claim value from your JWT tokens.

4.3 Map Token Claims to Piano Fields

  • External Identity Provider UID:

    • Map to the claim representing the user UID (typically sub).

  • Email Claim Name:

    • Typically email.

  • First Name Claim Name:

    • Typically given_name or first_name.

  • Last Name Claim Name:

    • Typically family_name or last_name.

  • Expiration Time Claim:

    • Ensure the exp claim is included; Identity Linking requires this claim.

  • Add Custom Claims:

    • Use the + Add a new claim button to map custom fields.

    • Enter the claim name and map it to the corresponding Identity Management field.

Ensure that fields do not contain any blank spaces, as this may cause login failures for end-users.

4.4 Select UID Creation Strategy

Choose the UID creation strategy that suits your implementation:

  1. External UID Connector API (Recommended if users may be created via Piano):

    • Allows Piano to request UID creation from your external system.

    • Requires implementing an API endpoint for UID creation.

    • Necessary for features requiring user creation outside your system (e.g., Subscribe with Google).

  2. UUID Strategy:

    • Piano generates UIDs in UUID format.

    • Requires handling user creation via webhooks in your system.

    • Suitable if your external system uses UUIDs and can process webhooks.

  3. UID Strategy:

    • Uses Piano's legacy 15-character UID format, prefixed with "PNI".

    • Requires handling user creation via webhooks.

4.5 Enable JTI Exclusivity (Recommended)

  • Enable the "Enable JTI exclusivity" toggle.

Benefits:

  • Reduces unnecessary updates to user profiles.

  • Improves performance by avoiding reprocessing tokens with known JTIs.

  • Prevents outdated tokens from overwriting recent changes.

This setting can only be enabled by a Piano administrator. Please contact your Piano representative to enable this setting.

5. Implement UID Creation Endpoint (If Using External UID Strategy)

5.1 Develop the UID Endpoint API

  • Create an API Endpoint:

    • Set up an endpoint that can handle GET requests from Piano.

    • The endpoint URL is configured in Identity Linking under "UID creation URL".

  • Security Considerations:

    • Ensure the endpoint can decrypt the data parameter received from Piano.

    • Use the Piano SDK's SecurityUtils class for decryption.

    • Implement appropriate security measures (e.g., validating origin, rate limiting).

5.2 Handle Incoming Requests

  • Process the Decrypted Payload:

    • The data parameter contains encrypted JSON with user information.

    • Decrypt the payload to retrieve fields like reason, email, first_name, last_name.

  • Create or Retrieve User UID:

    • If User Exists:

      • Find the user in your system based on the email.

      • Retrieve the user's UID.

    • If User Does Not Exist:

      • Create a new user using the provided information.

      • Generate a unique UID for the user.

  • Respond to Piano:

    • Return a JSON response with the following structure:

    {
      "uid": "user-unique-id",
      "registration": true or false,
      "passwordless": true or false
    }
    
    • Response Requirements:

      • HTTP status code must be 200 OK.

      • Response should be quick (Piano times out after 20 seconds).

      • Adhere to rate limits (maximum of 5 calls per second).

6. Implement JWT Generation in Authentication System

6.1 Ensure Proper Token Generation

  • Include All Required Claims:

    • Ensure your JWT tokens include all required standard and custom claims.

    • Verify that claim names match those configured in Piano.

  • Sign Tokens Correctly:

    • Use the specified algorithm (e.g., HS256, RS256).

    • Ensure the secret or key used matches what is configured in Piano.

6.2 Implement JTI Handling

  • Generate Unique jti for Each Token:

    • Each token should have a unique jti claim.

    • This prevents outdated tokens from affecting user profiles.

  • Token Expiration:

    • Set appropriate exp claim values to define token validity periods.

    • Encourage frequent token refreshes for security.

7. Add Piano JavaScript Library to Your Website

7.1 Include the Piano JavaScript

Insert the Script Before Composer Execution:

  tp = window.tp || [];
  tp.push(["setUseTinypassAccounts", false]);
  tp.push(["setUsePianoIdUserProvider", false]);
  tp.push(["setUsePianoIdLiteUserProvider", true]);

Placement:

  • Place this script in the <head> section or just before the closing </body> tag.

  • Ensure it's loaded before any Piano Composer scripts or experiences.

Alternative for HttpOnly Cookie Mode:

If using HttpOnly cookie authentication for enhanced security, use setExternalAuthCookieName instead:

tp.push(['setExternalAuthCookieName', 'your_cookie_name']);

Note: In HttpOnly mode, you will NOT use setExternalJWT in Step 9.

7.2 Set the Identity Management URL

Add the Following Script:

tp.push(['setPianoIdUrl', '']);

Replace <Piano_ID_URL> with the Appropriate URL:

  • AP Dashboard: https://id-ap.piano.io/

  • AU Dashboard: https://id-au.piano.io/

  • EU Dashboard: https://id-eu.piano.io/

  • US Dashboard: https://id.piano.io/

  • Sandbox Dashboard: https://sandbox.tinypass.com/

8. Test the Implementation in Sandbox

8.1 Verify Token Generation and Validation

Use the Piano Token Verification Endpoint:

https://sandbox.piano.io/id/api/v1/publisher/token/verify?aid={aid}&token={token}

Check the Response:

  • Ensure you receive an access_token.

  • Verify that the user is created in Piano if they do not already exist.

The previous endpoint is deprecated. Refer to the API documentation for details: Piano API Documentation.

8.2 Simulate User Authentication Flows

Test the Following Scenarios:

  • New User Registration:

    • Register a new user in your system.

    • Ensure the JWT token is generated and set correctly.

    • Verify the user is recognized by Piano.

  • User Login:

    • Log in with an existing user.

    • Ensure the JWT token reflects any updated information.

  • Token Expiration and Refresh:

    • Test behavior when tokens expire.

    • Verify that new tokens are issued and processed correctly.

In the Sandbox environment, user creation via JWT is limited. Users are only created in Piano under the following conditions:

  • A Composer experience including a Show Offer or a Show Template action is executed.

  • The user buys a subscription, updates a custom field, or opens the My Account profile tab.

  • When the /api/v1/publisher/token/verify request is executed.

8.3 Test User Data Synchronization

Update User Data:

  • Change user information (e.g., email, custom fields) in your system.

  • Generate a new token with updated claims.

Verify in Piano:

  • Confirm that updates are reflected in Piano user profiles.

  • Check that custom fields are correctly mapped and stored.

Test JTI Exclusivity:

  • Ensure that outdated tokens do not overwrite recent changes.

  • Observe the behavior when the same jti is used.

9. Set the External JWT Token on Every Page Load

9.1 Add Token Setting Script

Include the Following Script Early on Each Page:

tp.push(["setExternalJWT", ""]);
// Replace  with the actual JWT token

Replace <TOKEN> with the Actual JWT Token:

  • Generate the token upon user authentication.

  • Ensure the token is available to the script on every page load.

Alternative for HttpOnly Cookie Mode:

If using HttpOnly cookie authentication, skip this step. The JWT is automatically sent via an HttpOnly cookie on every request. Your authentication domain must generate and set the cookie with these attributes:

  • HttpOnly: true

  • Secure: true

  • SameSite: Lax

  • Domain: .yourdomain.com

  • Value: Valid JWT token

The cookie is set by your authentication system, not via Piano JavaScript.

If using HttpOnly cookie authentication, you must configure JavaScript Origins in the Identity Linking settings:

  1. Log in to the Piano Dashboard

  2. Navigate to Edit Business → User Provider → Identity Linking settings for your application

  3. Locate the JavaScript Origins section

  4. Add all domains where Piano JavaScript will execute (e.g., https://www.example.com, https://app.example.com)

  5. Save and confirm the whitelist

This configuration is required for CORS to work correctly with credential mode.

9.3 Important Considerations

Execution Order:

  • The token must be set before executing any Piano Composer experiences.

  • If loading scripts asynchronously, manage dependencies to prevent race conditions.

Consistency:

  • Set the token on every page load for authenticated users.

  • For anonymous users, ensure no token is set or clear any existing token.

Asynchronous Considerations:

  • Ensure token setting does not conflict with other asynchronous scripts.

  • Encountering race conditions between setting the token and experience execution will cause unexpected results.

  • There is one caveat to keep in mind for Identity Linking in Sandbox. Piano will create your user record from setting the JWT via Piano JS but in Sandbox there has to be an experience that targets the user with a Management + Billing action: either showOffer or showTemplate. As long as the JWT passes through an experience where a Management + Billing action occurs, you should see your user instantaneously in Piano. In Production you will not have this caveat and users will be created even without a Management + Billing action.

10. Implement loginRequired Event Handler

10.1 Handle Authentication Flow

Implement the loginRequired Event Handler:

tp.push(["addHandler", "loginRequired", function (params) {
    // Close any existing Piano offers if necessary
    tp.offer.close();

    // Initiate your authentication process
    yourAuthSystem.login().then(function () {
        // After successful login and token generation

        // Set the new JWT token
        tp.push(["setExternalJWT", ""]); // Replace  with the new JWT token

        // Resume the interrupted action
        tp.offer.startCheckout(params);
    });

    // Prevent default Piano login modal from appearing
    return false;
}]);

Notes:

  • params contains data needed to resume the checkout or offer flow. For more on the params object, see here.

  • Ensure the authentication process sets the token before resuming.

10.2 Handle Redirects (If Necessary)

If Your Authentication Involves Redirects:

Before Redirecting:

// Store the params object in a cookie or session storage
document.cookie = "__pianoParams=" + encodeURIComponent(JSON.stringify(params)) + "; path=/";

// Redirect to your authentication page
window.location.href = "https://your-authentication-page.com/login";

After Returning from Authentication:

// Retrieve the params object
var paramsCookie = decodeURIComponent(tp.util.findCookieByName('__pianoParams'));
var params = JSON.parse(paramsCookie);

// Set the JWT token
tp.push(["setExternalJWT", ""]); // Replace  with the new JWT token

// Resume the action
tp.offer.startCheckout(params);

// Clean up the cookie
document.cookie = "__pianoParams=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Clean Up: Remove the cookie after use to maintain security.

11. Configure User Data Webhooks (Optional)

11.1 Enable Webhooks in Piano Dashboard

  • Navigate to Manage > Webhooks in your Piano dashboard.

  • Enable the following user data webhooks as needed:

    • User created

    • User data updated

    • User disabled

    • User email confirmed

    • User updates custom field

11.2 Set Up Endpoint to Receive Webhooks (If Required)

  • Develop an Endpoint to Handle Webhooks:

    • The endpoint must accept POST requests from Piano.

    • Ensure it can parse JSON payloads.

  • Implement Security Measures:

    • Use secret tokens or signatures to verify webhook authenticity.

    • Respond with appropriate HTTP status codes (e.g., 200 OK).

  • Process Webhook Data:

    • Update user information in your system based on webhook events.

    • Handle actions like user disablement or email confirmation.

12. Ensure Compliance with Security and Privacy Policies

12.1 Data Protection and Privacy

  • Compliance:

    • Handle personal data in accordance with GDPR, CCPA, and other regulations.

    • Implement data minimization and purpose limitation principles.

  • User Rights:

    • Provide mechanisms for users to access, rectify, and delete their data.

    • Honor requests for data portability or erasure.

12.2 Token Security

  • Protect Secrets and Keys:

    • Store shared secrets and private keys securely.

    • Limit access to credentials to authorized personnel only.

  • Key Management:

    • Rotate secrets and keys periodically.

    • Update configurations in both your system and Piano after rotation.

  • Consent Management:

    • Obtain explicit user consent for data processing and sharing.

    • Keep records of consent and allow users to change preferences.

  • Privacy Policies:

    • Update your privacy policy to reflect data sharing with Piano.

Additional Resources:

Please refer to Piano's consent management approach for client storage cookies: Consent Management for Client Storage Cookies.

13. Deploy to Production

13.1 Migrate Configurations

  • Move Settings from Sandbox to Production:

    • Replicate Identity Linking configurations in the production Piano dashboard.

    • Update any environment-specific URLs and credentials.

13.2 Update Production Codebase

  • Implement Scripts and Handlers:

    • Ensure all necessary JavaScript snippets are included in production code.

    • Verify that the correct Identity Management URL is set for the production environment.

13.3 Final Testing

  • Perform Comprehensive Testing:

    • Test the full authentication flow in production.

    • Validate that tokens are being set and processed correctly.

  • Monitor Logs and User Feedback:

    • Keep an eye on authentication errors or user reports of issues.

    • Address any discrepancies promptly.

14. Monitor and Maintain

14.1 Ongoing Monitoring

  • Logging and Alerts:

    • Monitor logs for token validation errors or webhook failures.

    • Set up alerts for critical issues.

  • User Support:

    • Provide support channels for users experiencing access problems.

14.2 Performance Optimization

  • Asynchronous Operations:

    • Optimize the loading and execution of authentication scripts.

    • Avoid blocking the main thread or causing delays.

  • Endpoint Performance:

    • Ensure UID creation and webhook endpoints are responsive.

    • Scale infrastructure as needed to handle load.

14.3 Update Custom Fields and Claims

  • Adapt to Business Needs:

    • Add or modify custom claims as required.

    • Keep mappings in sync between your system and Piano (Custom field IDs need to match exactly in spelling and capitalization in the mapping).

  • Documentation:

    • Update internal documentation to reflect changes.

15. Additional Considerations

15.1 Mobile App Integration (If Applicable)

  • Configure Mobile SDKs:

    • Implement Identity Linking token setting in mobile applications.

    • Use Piano's mobile SDKs to integrate authentication flows.

Pass the JWT token as user access token before executing Composer:

Android (see Piano Android SDK Documentation):

Composer.getInstance().userToken(accessToken);

iOS (see Piano iOS SDK Documentation):

var composer = PianoComposer(aid: "")
.userToken("userToken") // set user token

Please note that you have to handle the registration and login process on your side (outside of Piano) and only generate a valid JWT that you pass on to the Piano mobile SDK.

15.2 Subscribe with Google Integration (If Applicable)

  • Follow Piano's Guidelines:

    • Refer to Piano's documentation on integrating Subscribe with Google.

    • Ensure provisional tokens are properly handled and verified.

15.3 Multiple Identity Providers (Optional)

  • Add Additional Providers:

    • In Identity Linking settings, click + Add external identity provider.

    • Configure each provider with its own credentials and claim mappings.

  • Considerations:

    • Ensure that user UIDs are unique across providers.

    • Handle token setting and validation for each provider appropriately.

16. Documentation and Training

16.1 Internal Documentation

  • Record Configurations:

    • Document all Identity Linking settings, endpoints, and credentials.

    • Maintain version control of scripts and code snippets.

  • Security Practices:

    • Keep documentation secure and accessible to authorized personnel.

16.2 Team Training

  • Educate Staff:

    • Train development and support teams on the Identity Linking implementation.

    • Provide troubleshooting guides and escalation procedures.

16.3 Support and Maintenance Plan

  • Assign Responsibilities:

    • Designate team members for ongoing maintenance.

    • Establish processes for handling incidents and updates.

  • Continuous Improvement:

    • Schedule periodic reviews of the implementation.

    • Stay informed about updates to Piano's platform and best practices.

By following this implementation checklist, you will successfully integrate your external authentication system with Identity Management Identity Linking. This will enable seamless user experiences, improved data synchronization, and access to Piano's advanced features while maintaining control over your authentication processes.

Last updated: October 17th 2024

Last updated: