Custom sign-in button (add a click handler)

The Trade Desk recommends using the OpenPass JavaScript SDK for creating a client-side JavaScript integration. This SDK provides a secure and user-friendly Sign In with OpenPass button or inline sign-in form that can be customized according to your requirements. However, you have the option to add a sign-in button yourself.

This quickstart helps you create an OpenPass client to integrate with your website and implement single sign-on (SSO) for the open internet with the option of adding your own sign-in button. Follow these instructions to install the SDK with your own sign-in button, then configure your site to reference it.

IMPORTANT: To use the popup flow and inline sign-in form options, ensure that your website has a secure origin. This means that your website should have an HTTPS address.
If you're using a localhost origin for development purposes, create a separate application for that purpose. This ensures that localhost is never allowed on your production configurations.
If you're also using the fallback-to-redirect option for the popup flow, which is used when the popup fails to open, you need to configure a redirect URL.
Inline sign-in requires a content security policy that allows embedding the iframe on your site. You must configure the application to include all the origins where the inline sign-in form will be used.

Step Description Notes
1 Install the SDK. You can use a content delivery network (CDN) or node package manager (NPM).
2 Initialize the OpenPass client. N/A
3 Add the sign-in button yourself. N/A
4 Implement an authentication flow. To brush up on the differences between flows, see the JavaScript overview.

The following sections detail each step.

1. Install the SDK

You can install the SDK on a CDN or use NPM.

Installing using CDN has limitations. Unlike NPM, developers have limited control over the code they can use for shipping when compiling, and they cannot deploy or optimize JavaScript bundles by including dependencies like OpenPass. Also, some developers prefer to fix versions in NPM.

CDN

To install on a CDN, run the following command.

<script src="https://cdn.myopenpass.com/openpass-js-sdk/v4/openpass-js-sdk.min.js"></script>

NPM

To install using NPM, run the following command in your project.

npm install @openpass/openpass-js-sdk

In your code, reference the library. Here is an example:

// ES6 / TypeScript
import { OpenPassClient } from "@openpass/openpass-js-sdk";

When completed, go to the following step.

2. Initialize the OpenPass client

The OpenPass client in your web application manages the link generation for your sign-in button and handles the results of user sign-ins.

To initialize an instance of the OpenPass client, update the option parameters in the new OpenPassClient(options) method. The client is created once in your application and referenced in the appropriate places.

openPassClient = new OpenPassClient({ clientId: "{{clientId}}" });

When initialization is complete, go to the following step.

3. Add a click handler to the sign-in button

Determine your authentication flow, then follow its instructions for adding a sign-in button.

Flow Description
Redirect For when the browser or app redirects the entire page to the OpenPass Universal Login sign-in form, and then back to your site when the user has completed the sign-in.
Popup For when the browser or app opens an OpenPass sign-in popup window separate from the originating page. When the sign-in is complete, the popup closes and a message is sent back to your site notifying that the user has signed in.

Redirect

The following code example adds a click handler to the Sign In with OpenPass button. It provides the redirect URL for finalizing the authentication process and the originating URL for returning the user to the site after authentication.

signInButton.addEventListener("click", () => {
  openPassClient.signInWithRedirect({

    // The URI on your site that OpenPass redirects back to, which then finalizes the authentication process.
    redirectUrl: "HTTPS_HANDLE_OP_REDIRECT_URL";
  });
});

After implementing this code, skip to the Handle the authentication response section.

Popup

The following code example adds a click handler to the Sign In with OpenPass button in the popup flow. It logs the user's email address, passes it to your organization in an ID token, and provides the originating URL for returning the user to the site after authentication. If the sign-in page loads successfully, it runs a redirect to the originating page that triggered the sign-in. Otherwise, the user will be directed to the full-page OpenPass sign-in form.

signInButton.addEventListener("click", () => {
openPassClient
    .signInWithPopup({
       redirectUrl: "HTTPS_HANDLE_OP_REDIRECT_URL",
        clientState: {
            originalUrl: window.location.origin + "/article-sign-in-popup"
        }
    })
    .then((signInResponse)=> {

        // Access the user's email address and user ID from the response.
        const email = signInResponse.idToken.email; 
        const openpassUserId = signInResponse.idToken.sub;

        // Set up the user's session on your site. This step is controlled by you and depends on your user state management implementation. 
        startUserSession(openpassUserId, email); 

        // Connect the user to UID2.
        setUpUid2Identifier(email);

        // Redirect the user back to the original content.
        window.location = signInResponse.originatingUri;

    }).catch((error) => {
        // log the error
        console.error(JSON.stringify(error));

        // Decide what to do if the sign-in fails (for example, the user closes the popup before authenticating):
        window.location = "/login";
    });
});

For details on user state management implementation, see openPassClient.signInWithPopup(options) ⇒ Promise. For details on UID2 implementation, see Unlock greater potential with UID2.

After implementing this code, if you are using the redirect mode, go to the following step.

If you are using the popup mode, this section completes the installation process. The authentication response will be handled by the then handler referenced in the previous code example. To verify the OpenPass ID token, see Verify the ID token. For next steps, see Additional resources.

4. Handle the authentication response for redirect

To handle the OpenPass authorization-code redirect to finalize the authentication flow, the redirect flow uses isRedirect() and handleAuthenticationRedirect().

IMPORTANT: Make sure that the redirect URI you provide to the signInWithRedirect() method matches one of the redirect URIs specified in your OpenPass account. You also need to configure the redirect URL in the application settings for your client.

To handle the redirect authentication response, use the following code example to complete the authentication process and handle the redirect from the sign-in button. If the sign-in is successful, you may redirect the user to the originating page that triggered the sign-in. But if there is an exception, you can choose to redirect them to an error page instead.

// Example: on route HTTPS_HANDLE_OP_REDIRECT_URL

// Check if this page was loaded by means of an OpenPass redirect.
if (openPassClient.isAuthenticationRedirect()) {
  try {
    // The following reads the authorization code from the OpenPass redirect request and 
    //exchanges it for an ID token and an access token.
    const signInResponse = await openPassClient.handleAuthenticationRedirect();

    // Access the user's email address and user ID from the response.
    const email = signInResponse.idToken.email; 
    const openpassUserId = signInResponse.idToken.sub;

    // Set up the user's session on your site. This step is controlled by you and depends on your user state management implementation. 
    startUserSession(openpassUserId, email); 

    // Connect the user to UID2.
    setUpUid2Identifier(email);

    // Redirect the user back to the original content.
    window.location = signInResponse.originatingUri;
  } catch (error) {
    // log the error
    console.error(JSON.stringify(error));

    // Decide what to do if the sign-in fails (for example, the user closes the popup before authenticating):
    window.location = "/login";
  }
}

Handling the authentication response completes the installation process. To verify the OpenPass ID token, see Verify the ID token.

Next steps

Here are some suggestions for enhancing OpenPass functionality and the user experience:

Additional resources

For more information, see the following pages: