OpenPass SDK for JavaScript reference
For background information on the OpenPass service, and general information on implementation, see Getting started with OpenPass.
The following table summarizes the SDK methods available.
| Method | Description |
|---|---|
| new OpenPassClient(options) | Creates a new instance of the OpenPassClient. |
| openPassClient.renderSignInButton(options) ⇒ void | Automatically renders a "Sign In with OpenPass" button with one of three text options, and integrates it with either the redirect or popup flow. This can be done through an HTML or JavaScript API. |
| openPassClient.renderInlineSignInForm(options) ⇒ void | Renders the sign-in form directly within a web page and places the publisher's logo and display name on the first lines of the sign-in form, rather than next to the OpenPass brand. Includes the dark mode option. |
| openpassClient.renderQuickAuth(options) ⇒ Promise | Renders a QuickAuth sign-in form directly within a web page using fewer authentication steps than the other OpenPass sign-in methods. With QuickAuth, users who are already signed in to OpenPass on their device can seamlessly authenticate to your website or app with a single click. Includes an optional fallback to a full-page redirect sign-in if it's not possible to create a popup window. |
| openPassClient.signInWithRedirect(options) ⇒ Promise | Initiates a full-page redirect OpenPass sign-in. This method first redirects the user to the OpenPass authorization server and then, when authorization is complete, redirects back to the specified redirect URI. |
| openPassClient.signInWithPopup(options) ⇒ Promise | Initiates an OpenPass sign-in in a popup window, with an optional fallback to a full-page redirect sign-in if it's not possible to create a popup window. |
| openPassClient.authorizeDevice(options) ⇒ Promise | Initiates the OpenPass device authorization grant. This should be called on the device that wishes to authenticate, such as a TV. |
| openPassClient.deviceToken(options) ⇒ Promise | Check the status of the device token request. This should be called on the device that initiated the device authorization grant. |
| openPassClient.isAuthenticationRedirect() ⇒ boolean | Returns true if the current page was redirected by the OpenPass authentication process after a successful or unsuccessful user sign-in. |
| openPassClient.handleAuthenticationRedirect() ⇒ Promise | Call this method to complete the OpenPass authentication flow in response to receiving a callback to a redirect URI from OpenPass. |
The end of this document details the parameters used by three of the SDK elements in the sign-in process: the sign-in response, ID token, and error message.
(options)
Creates a new instance of the OpenPassClient.
| Parameter | Data Type | Default | Description |
|---|---|---|---|
options |
OpenPassOptions |
N/A | The options to initialize the client. |
options.clientId |
string |
N/A | The client ID of the application. |
openPassClient.renderSignInButton(options) ⇒ void
Automatically renders a "Sign In with OpenPass" button with one of three text options, and integrates it with either the redirect or popup flow.
There are two ways to integrate with the Sign In with OpenPass button:
- HTML API: The SDK registers a
DOMContentLoadedloaded callback, and then looks for an element in the DOM with the idsign-in-with-openpass-buttonand will place the button inside that container element. The SDK usesdata-*attributes to configure the button. - JavaScript API: The OpenPassClient provides a
renderSignInButtonmethod which you can use to render the button into a provided parent element ID. This means you can place multiple sign-in buttons onto a single page if required, or control exactly when you want to render the button, such as when a modal window is opened.
For examples of styling options, see Sign-in button samples.
Html API redirect
The following code example renders the Sign In with OpenPass button using HTML. If the sign-in popup page loads successfully, it runs a redirect to the originating page that triggered the sign-in. Otherwise, it redirects to an error page.
<div id="sign-in-with-openpass-button" data-mode="redirect" data-text="signin_with" data-client-id="CLIENT_ID" data-redirect-uri="REDIRECT_URI"></div>
Html API popup
The following code example renders the Sign In with OpenPass button in a popup window using HTML. If the sign-in popup 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.
<div id="sign-in-with-openpass-button" data-mode="popup" data-text="signin_with" data-client-id="CLIENT_ID" data-redirect-uri="REDIRECT_URI" data-popup-success-callback="popupSuccessCallback" data-popup-failed-callback="popupFailedCallback"></div>
<script>
window.popupSuccessCallback = (signInResponse) => {
// Handle successful sign-in here
};
window.popupFailedCallback = (error) => {
// Handle failed sign-in here
};
</script>
Html API reference
The following table lists the parameters:| Parameter | Attribute Name | Required? | Data Type | Description |
|---|---|---|---|---|
| Authentication Mode | data-mode |
No | string |
The authentication mode type: redirect or popup. Defaults to redirect. |
| Client ID | data-client-id |
Yes | string |
The client ID, which is obtained from the partner portal. |
| Redirect URI | data-redirect-uri |
Yes (if mode is redirect) |
string |
Specifies the URL to which the user will be redirected when authentication is set to the redirect mode. This is optional when using the popup mode. |
| Popup Success Callback | data-popup-success-callback |
Yes (if mode is popup) |
string |
A callback function name, which accepts a SignInResponse as a parameter, to invoke when the popup sign-in succeeds. The function should exist in the global scope of the window. |
| Popup Failed Callback | data-popup-failed-callback |
No | string |
An optional callback function name, which accepts SdkError as a parameter, to invoke when the popup sign-in fails. The function should exist in the global scope of the window. |
| Shape | data-shape |
No | string |
Controls the shape of the button. Valid values: standard (default), icon. |
| Shape Variant | data-shape-variant |
No | string |
Controls the shape variant of the button. Valid values for the standard shape: pill (default), data-rectangle. Valid values for the icon shape: square, circle |
| Size | data-size |
No | string |
Controls the size of the button. Valid values: x-large, large (default), medium, small. |
| Text | data-text |
No | string |
Controls the text displayed inside the button. Valid values: signin_with (default), signin, continue_with. |
| Theme | data-theme |
No | string |
Controls the theme of the button. Valid values: openpass (default), light, dark. |
| Additional Width | data-additional-width |
No | number |
Controls where additional width is applied to the button. |
JavaScript API redirect
The following code example renders the Sign In with OpenPass button using JavaScript. If the sign-in page loads successfully, it runs a redirect to the originating page that triggered the sign-in. Otherwise, it redirects to an error page.
window.addEventListener("DOMContentLoaded", async () => {
const openPassClient = new OpenPassClient({
clientId: "CLIENT_ID",
});
openPassClient.renderSignInButton({
parentContainerElementId: "HTML_ELEMENT_ID",
authenticationMode: "redirect",
redirectUrl: "REDIRECT_URI",
text: "signin_with",
});
});
Tip: To render the button, use the JavaScript
DOMContentLoadedevent as the trigger. Using theloadevent might delay rendering.
JavaScript API popup
The following code example renders the Sign In with OpenPass button in a popup window using JavaScript. 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.
window.addEventListener("DOMContentLoaded", async () => {
const openPassClient = new OpenPassClient({
clientId: "CLIENT_ID",
});
openPassClient.renderSignInButton({
parentContainerElementId: "HTML_ELEMENT_ID",
authenticationMode: "popup",
redirectUrl: "REDIRECT_URI",
text: "signin_with",
popupSuccessCallback: (signInResponse) => {
// Handle successful sign-in here
},
popupFailedCallback: (error) => {
// Handle failed sign-in here
},
});
});
Tip: To render the button, use the JavaScript
DOMContentLoadedevent as the trigger. Using theloadevent might delay rendering.
openPassClient.renderInlineSignInForm(options) ⇒ void
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.
Renders the sign-in form directly within a web page and places the publisher's logo and display name on the first lines of the sign-in form, rather than next to the OpenPass brand. Includes the dark mode option.
The following example shows the inline sign-in form option. It uses the same authentication process and has the same responses as either the redirect or popup flow.
const popupSuccessCallback = (response) => {
console.log(JSON.stringify(response));
};
const popupFailedCallback = (error) => {
console.log(JSON.stringify(error));
};
const options = {
parentContainerElementId: "form-container",
authenticationMode: "popup",
popupSuccessCallback: popupSuccessCallback,
popupFailureCallback: popupFailureCallback,
signinButtonTextOption: "signin",
};
The following table lists the parameters:
| Parameter | Required? | Data Type | Description |
|---|---|---|---|
parentContainerElementId |
Yes | string |
Specifies the ID of the HTML element where the sign-in form is inserted. This is usually a div element large enough to wrap around the sign-in form. |
authenticationMode |
Yes | AuthenticationModeType |
This determines how the sign-in process is handled, either by redirecting the user to a new page or opening a popup window. Choose from these options:
|
redirectUrl |
Yes (when in redirect mode) | string |
Specifies the URL the user will be redirected to when authentication is set to the redirect mode. This is optional when using the popup mode. |
clientState |
No | Record<string, string> |
Can be used to maintain the state between the sign-in request and callback. |
signinButtonTextOption |
No | SignInButtonTextOption |
Enter an option to display in the Sign In with OpenPass button:
|
darkModeEnabled |
No | boolean |
Inverts the text color of the inline sign-in form to white instead of black, including the logo next to the phrase "Powered by." |
signinButtonBackgroundColorHex |
No | string |
Specifies the color to override background color of the sign in button in hex format. For example: #000333 |
popupSuccessCallback |
Yes (if mode is popup) |
(response: SignInResponse) => void |
Applies only to the popup option. This function is called when sign-in is successful. It receives a sign in response object as a parameter. |
popupFailedCallback |
No | (error: SdkError) => void |
Applies only to the popup option. This function is called when sign-in fails. It receives an SdkError as a parameter, which contains the error.For example, this error indicates an invalid authentication mode option: Error: Invalid authentication mode: wrong_authentication_mode. |
popupSignInInitiatedCallback |
Yes (if mode is popup) |
options.popupSignInInitiatedCallback |
This function is called when a sign-in is initiated. |
widthInPixels |
No | number |
Sets the width of the inline sign-in form iframe. Defaults to 100% if not specified. |
heightInPixels |
No | number |
Sets the height of the inline sign-in form iframe. Defaults to 100% if not specified. |
signinButtonBorderRadiusInPixels |
No | number |
Customize the sign-in button's rounded corners by setting the border radius. |
hideSignInFormApplicationLogo |
No | boolean |
Set this parameter to true to hide the application logo on the sign-in form. |
hideSignInFormHeaderText |
No | boolean |
Set this parameter to true to hide the header text on the sign-in form. |
The code then starts the sign-in process. A successful sign-in response returns the following properties:
idToken: The decoded ID token, which contains the user's identity details (including their email address).rawIdToken: The raw ID token string (JWT), which contains the users identity details (including their email address).accessToken: The access token string, which can be used to do Bearer authorization against the OpenPass API.clientState: Thestatevalue, which is passed to thesignInWithPopup()(for popup with fallback to redirect) andsignInWithRedirect()flows.
If the provided sign-in options fail the validation rules, it writes an error message to the browser's console.
try {
await openPassClient.renderInlineSignInForm(signInOptions);
} catch (e) {
// If there are any issues with the sign-in options supplied
console.error(e);
}
Tip: To render the sign-in form, use the JavaScript
DOMContentLoadedevent as the trigger. Using theloadevent might delay rendering.
JavaScript API reference
The following table lists the parameters:
| Parameter | Options Parameter | Required? | Data Type | Description |
|---|---|---|---|---|
| Parent Container Element Id | parentContainerElementId |
Yes | string |
The parent container element ID for rendering the Sign In with OpenPassn button. |
| Authentication Mode | authenticationMode |
Yes | string |
The authentication mode type: redirect or popup. |
| Redirect URI | redirectUrl |
No | string |
The redirect URI, which can be specified when using the popup mode and will be used as a fallback if the popup window cannot be opened. |
| Popup Success Callback | popupSuccessCallback |
Yes (if mode is redirect) |
string |
A callback function, which accepts a SignInResponse as a parameter, to invoke when the popup sign-in succeeds. |
| Popup Failed Callback | popupFailedCallback |
No | string |
An optional callback function, which accepts SdkError as a parameter, to invoke when the popup sign-in fails. |
| Login Hint | loginHint |
No | string |
An optional hint for the login email address identifier the user might log in with. |
| Shape | shape |
No | string |
Controls the shape of the button. Valid values: standard (default), icon. |
| Shape Variant | shapeVariant |
No | string |
Controls the shape variant of the button. Valid values for standard shape: pill (default), rectangle. Valid values for icon shape: square, circle |
| Size | size |
No | string |
Controls the size of the button. Valid values: x-large, large (default), medium, small. |
| Text | text |
No | string |
Controls the text displayed inside the button. Valid values: signin_with (default), signin, continue_with. |
| Theme | theme |
No | string |
Controls the theme of the button. Valid values: openpass (default), light, dark. |
| Additional Width | additionalWidth |
No | number |
Controls where additional width is applied to the button. |
openpassClient.renderQuickAuth(options) ⇒ Promise<void>
IMPORTANT: To use QuickAuth, ensure that you have a client ID and your website has a secure origin.
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.
QuickAuth 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 QuickAuth sign-in form will be used.
Renders a QuickAuth sign-in form directly within a web page for a more seamless and integrated user experience. With QuickAuth, users who are already signed in to OpenPass on their device can seamlessly authenticate to your website or app with a single click.
There are two ways to integrate QuickAuth:
- HTML API: Depending on your setup, this might be the easiest option.
- JavaScript API: Renders programmatically and requires more steps, such as instantiating the client, passing correct arguments, and renaming the div ID.
TIP: For a better developer experience, you can use the QuickAuth HTML and QuickAuth JavaScript templates in GitHub for reference.
Html API
If you are using the HTML option, you can implement it using either the redirect or popup authentication flow.
Redirect
The following code example renders QuickAuth using HTML. If it loads successfully, it runs a redirect to the originating page that triggered the sign-in. Otherwise, it redirects to an error page.
<main>
<div>
<div id="openpass-quick-auth" data-openpass-quick-auth-client-id="CLIENT_ID" data-openpass-quick-auth-mode="redirect" data-openpass-quick-auth-redirect-uri="REDIRECT_URI"></div>
</div>
</main>
;
Popup
The following code example renders QuickAuth using HTML. If it loads successfully, it runs a redirect to the originating page that triggered the sign-in. Otherwise, it redirects to the full-page OpenPass sign-in form.
<main>
<div>
<div id="openpass-quick-auth" data-openpass-quick-auth-client-id="CLIENT_ID" data-openpass-quick-auth-mode="popup" data-openpass-quick-auth-redirect-uri="REDIRECT_URI" data-openpass-quick-auth-popup-success-callback="popupSuccessCallback" data-openpass-quick-auth-popup-failed-callback="popupFailedCallback" data-openpass-quick-auth-visibility-changed-callback="visibilityChangedCallback"></div>
</div>
<script>
function popupSuccessCallback(signInResponse) {
console.log("Popup flow sign in succeeded, email address: " + signInResponse.idToken.email);
}
function popupFailedCallback(error) {
console.log("Popup flow sign in failed, error: " + error.message);
}
function visibilityChangedCallback(data) {
console.log("QuickAuth visibility changed: " + data.visibility);
}
</script>
</main>
;
The code then starts the sign-in process. A successful sign-in response returns the following properties:
idToken: The decoded ID token, which contains the user's identity details (including their email address).rawIdToken: The raw ID token string (JWT), which contains the users identity details (including their email address).accessToken: The access token string, which can be used to do Bearer authorization against the OpenPass API.clientState: Thestatevalue, which is passed to thesignInWithPopup()(for popup with fallback to redirect) andsignInWithRedirect()flows.
Html reference
The following table lists the parameters:
| Parameter | Required? | Data Type | Description |
|---|---|---|---|
id |
Yes | string |
Must be openpass-quick-auth. |
data-openpass-quick-auth-client-id |
Yes | string |
Enter the client ID you received after registering with OpenPass. |
data-openpass-quick-auth-mode |
Yes | string |
This determines how the sign-in process is handled, either by redirecting the user to a new page or opening a popup window. Choose from these options:
|
data-openpass-quick-auth-redirect-uri |
Yes (when in redirect mode) | string |
Specifies the URL the user will be redirected to when authentication is set to the redirect mode. This is optional when using the popup mode. |
data-openpass-quick-auth-popup-success-callback |
Yes (if mode is popup) |
string |
Applies only to the popup option. It is the name of the function which is called when sign-in is successful. It receives a sign in response object as a parameter. |
data-openpass-quick-auth-popup-failed-callback |
No | string |
Applies only to the popup option. It is the name of the function which is called when sign-in fails. It receives an SdkError as a parameter, which contains the error.For example, this error indicates an invalid authentication mode option: Error: Invalid authentication mode: wrong_authentication_mode. |
data-openpass-quick-auth-visibility |
No | string |
Determines the visibility of the quick-auth sign-in form. Enter one of the following:
displayOnInit. |
data-openpass-quick-auth-visibility-changed-callback |
No | string |
Specify a callback which is called on each QuickAuth visibility change. The payload contains a object with a visibility property that can be one of the following values:
|
JavaScript
If you are using the HTML option, you can implement it using either the redirect or popup authentication flow.
TIP: Using the
loadevent can delay rendering, so we recommend using theDOMContentLoadedevent instead. See the following code example.
Redirect
To render QuickAuth using JavaScript, use the following code snippet. Be sure to instantiate the client and pass the correct arguments.
window.addEventListener("DOMContentLoaded", async () => {
const openpassClient = new OpenPassClient({
clientId: "CLIENT_ID",
});
try {
openpassClient.renderQuickAuth({
parentContainerElementId: "HTML_ELEMENT_ID",
authenticationMode: "redirect",
redirectUrl: "REDIRECT_URI",
});
} catch (e) {
console.error(e);
}
});
Popup
To render the popup using JavaScript, use the following code snippet. Be sure to instantiate the client and pass the correct arguments.
NOTE: You can programatically hide and show QuickAuth using the functions
openpassClient.hideQuickAuthSignIn();andopenpassClient.showQuickAuthSignIn();.
window.addEventListener("DOMContentLoaded", async () => {
const openpassClient = new OpenPassClient({
clientId: "CLIENT_ID",
});
try {
openpassClient.renderQuickAuth({
parentContainerElementId: "HTML_ELEMENT_ID",
authenticationMode: "popup",
redirectUrl: "REDIRECT_URI",
popupSuccessCallback,
popupFailedCallback,
visibility: "displayOnInit",
visibilityChangedCallback,
});
} catch (e) {
console.error(e);
}
function popupSuccessCallback(signInResponse) {
console.log("Popup flow sign in succeeded, email address: " + signInResponse.idToken.email);
}
function popupFailedCallback(error) {
console.log("Popup flow sign in failed, error: " + error.message);
}
function visibilityChangedCallback(data) {
console.log("QuickAuth visibility changed: " + data.visibility);
}
});
JavaScript reference
The following table lists the parameters:
| Parameter | Required? | Data Type | Description |
|---|---|---|---|
parentContainerElementId |
Yes | string | The name of the HTML element that QuickAuth will attach to. It is reccommended that this element is placed in the root of your HTML body, and no styles are applied. For example, use a div with openpass-quick-auth as the ID: <div id="openpass-quick-auth"></div> |
authenticationMode |
Yes | AuthenticationModeType |
This determines how the sign-in process is handled, either by redirecting the user to a new page or opening a popup window. Choose from these options:
|
redirectUrl |
Yes (when in redirect mode) | string |
Specifies the URL the user will be redirected to when authentication is set to the redirect mode. This is optional when using the popup mode. |
clientState |
No | Record<string, string> |
Can be used to maintain the state between the sign-in request and callback. |
popupSuccessCallback |
Yes (if mode is popup) |
(response: SignInResponse) => void |
Applies only to the popup option. This function is called when sign-in is successful. It receives a sign in response object as a parameter. |
popupFailedCallback |
No | (error: SdkError) => void |
Applies only to the popup option. This function is called when sign-in fails. It receives an SdkError as a parameter, which contains the error.For example, this error indicates an invalid authentication mode option: Error: Invalid authentication mode: wrong_authentication_mode. |
visibility |
No | VisibilityType |
Determines the visibility of the quick-auth sign-in form. Enter one of the following:
displayOnInit. |
visibilityChangedCallback |
No | (data: VisibilityChangedData) => void |
Specify a callback which is called on each QuickAuth visibility change. The payload contains a object with a visibility property that can be one of the following values:
|
delayMs |
No | number |
The delay in milliseconds before QuickAuth is displayed when renderQuickAuth is called.
1000. It is not recommended that you override the default. |
openPassClient.signInWithRedirect(options) ⇒ Promise<void>
Initiates a full-page redirect OpenPass sign-in. This method first redirects the user to the OpenPass authorization server and then, when authorization is complete, redirects back to the specified redirect URI.
| Parameter | Required? | Data Type | Description |
|---|---|---|---|
options |
Yes | RedirectSignInOptions |
Redirect sign-in options. |
options.redirectUri |
Yes | string |
A valid redirect URI that processes a callback from the OpenPass authorization server. The URI must match a redirect URI you have configured with OpenPass. |
options.clientState |
No | Record<string, string> |
An optional object containing any client-side state value that is stored and then returned back when authentication is complete. You can use this to store the original URL and then redirect back to after a successful authentication. |
options.loginHint |
No | string |
An optional hint for the login email address identifier the user might log in with. |
options.consentJwt |
No | string |
An optional JWT to prove that the user has seen the OpenPass and client's terms and conditions and privacy policy. This token is generated by OpenPass in certain scenarios, such as when the user is shown the in-line sign-in form. It should not be manually generated by the client. |
options.disableLoginHintEditing |
No | string |
If a login hint is provided, this can be set to |
openPassClient.signInWithPopup(options) ⇒ Promise<SignInResponse>
Initiates an OpenPass sign-in in a popup window, with an optional fallback to a full-page redirect sign-in if it's not possible to create a popup window.
A fallback to a full-page redirect happens in these scenarios:
- A fallback redirect URL is provided.
- The device width or height is too small.
- A popup cannot be opened. For example, it is blocked.
If a fallback redirect URL is not provided to enable the fallback mode, and the popup window fails to open, an SdkError error will be thrown.
The following example shows the popup flow.
try {
const signInResponse = await openPassClient.signInWithPopup({
redirectUrl: [Your_Redirect_URL],
clientState: [Your_Client_State],
});
console.log(signInResponse.idToken);
console.log(signInResponse.clientState);
} catch (e) {
console.log(e);
}
It is also necessary to manage the authentication redirect if the full-page redirect sign-in is triggered. To do this, use the handleAuthenticationRedirect method.
Sample response
The signInWithPopup() and handleAuthenticationRedirect methods both return a response of type SignInResponse, with the following properties:
idToken: The decoded ID token, which contains the user's identity details (including their email address).rawIdToken: The raw ID token string (JWT), which contains the users identity details (including their email address).accessToken: The access token string, which can be used to do Bearer authorization against the OpenPass API.originatingUri: The originating window URI that the user was on when the authentication flow was initiated. This could be used by the redirect authentication flow to redirect the user back to the page that initiated the sign-in.clientState: Thestatevalue, which is passed to thesignInWithPopup()(for popup with fallback to redirect) andsignInWithRedirect()flows.
| Parameter | Required? | Data Type | Description |
|---|---|---|---|
options |
Yes | PopupSignInOptions |
Popup Sign-in options |
options.redirectUri |
No | string |
An optional valid redirect URI that processes a callback from the OpenPass authorization server. This will be used as a fallback if the popup window fails to open. The URL must match a redirect URI you have configured with OpenPass. |
options.clientState |
An optional object containing any client-side state value that is stored and then returned after authentication. You can use this to store the original URL and redirect the user back after successful authentication. |
Record<string, string> |
|
options.loginHint |
No | string |
An optional hint for the login email address identifier the user might log in with. |
options.consentJwt |
No | string |
An optional JWT to prove that the user has seen the OpenPass and client's terms and conditions, as well as the privacy policy. This token is generated by OpenPass in certain scenarios, such as when the user is shown the in-line sign-in form. It should not be manually generated by the client. |
options.disableLoginHintEditing |
No | string |
If a login hint is provided, this can be set to true to prevent the user from changing the sign-in email address. |
openPassClient.authorizeDevice(options) ⇒ Promise<AuthorizeDeviceData>
Initiates the OpenPass device authorization grant. This should be called on the device that wishes to authenticate, such as a TV.
Once initiated, you should prompt the user to finish the authentication on another device by using the user code or verification URI provided in the result of this method call.
The following example shows how to initiate the flow.
try {
const authorizeDeviceData = await openpassClient.authorizeDevice({});
// Display this link (via QR code or other means) to the user to complete the authentication on another device.
console.log(authorizeDeviceData.verificationUriComplete);
} catch (e) {
console.log(e);
}
The following table lists the parameters:
| Parameter | Required? | Data Type | Description |
|---|---|---|---|
loginHint |
No | string |
A hint for the login email address identifier the user might log in with. |
disableLoginHintEditing |
No | string |
If a login hint is provided, this can be set to true to prevent the user from changing the sign-in email address. |
Sample response
{
"deviceCode": "FBYH2Bq9El88WSTiAVTaXgAAAAAAAAAA",
"userCode": "XSAEQM1V",
"verificationUri": "https://myopenpass.com/code",
"verificationUriComplete": "https://myopenpass.com/code?user_code=XSAEQM1V",
"expiresIn": 500,
"interval": 5
}
The following table lists the response fields:
| Field | Required? | Data Type | Description |
|---|---|---|---|
deviceCode |
Yes | string |
The device code to be used by the device for polling the device-token endpoint to retrieve the access token. |
userCode |
Yes | string |
A user-friendly code that is typically displayed on the device for the subject to register or reject the device registration. |
verificationUri |
Yes | string |
The verification URI where the user can navigate to authorize the device by entering the user code. |
verificationUriComplete |
Yes | string |
The verification URI that contains the user code as an HTTP query parameter typically displayed on the device as part of the QR code. |
expiresIn |
Yes | number |
The duration in seconds indicating the maximum time the device should poll for the registration result and the amount of time the user has to complete the device registration. |
interval |
Yes | number |
The number of seconds that the device should wait between polling requests to the device-token endpoint. |
Next steps
Once you receive the device authorization response, you must display the verificationUri link (via QR code or other means) to the user so they can authenticate on another device. In the meantime, you then need to poll the deviceToken(options) ⇒ Promise<DeviceTokenWithStatus> method to check for the completion of the user's authentication.
openPassClient.deviceToken(options) ⇒ Promise<DeviceTokenOptions>
Check the status of the device token request. This should be called on the device that initiated the device authorization grant.
Once the user has authenticated on another device, this method will return an `ok` status and the OpenPass tokens (ID token, access token).
If the authentication is still pending, the status will be `authorization_pending` or `slow_down`. Poll the endpoint again after the interval provided in the result of the authorizeDevice(options) ⇒ Promise<AuthorizeDeviceData> method.
The following example shows how to check the device token status.
try {
// wait `authorizeDeviceData.interval` seconds
// Check the status of the device token request.
const deviceTokenWithStatus = await openpassClient.deviceToken({ deviceCode: authorizeDeviceData.deviceCode });
if (deviceTokenWithStatus.status === "ok") {
console.log("User authenticated on another device. Id token: " + deviceTokenWithStatus.tokens.idToken);
} else if (deviceTokenWithStatus.status === "authorization_pending") {
console.log("Authorization pending...");
// wait `authorizeDeviceData.interval` seconds before next poll
} else if (deviceTokenWithStatus.status === "slow_down") {
console.log("Authorization pending, slow down polling...");
// wait (`authorizeDeviceData.interval` x multiplier) seconds before next poll
}
} catch (e) {
console.log(e);
}
To enable polling and monitor the result from the deviceToken method each time, use the following setInterval code example and specify the number of attempts.
// Poll for the device token using setInterval. Other techniques can be used, such as setTimeout or async/await with a delay.
let pollingInterval = setInterval(async () => {
// A counter can be used to stop polling after a certain number of attempts.
counter++;
// Stop polling if polling is not enabled, or after a specified number of attempts.
// Note: You can implement other logic to stop polling.
if (!isPollingEnabled() || counter > maxPollingAttempts) {
// To stop polling, clear the interval.
clearInterval(pollingInterval);
return;
}
try {
// Call the get device token method.
const deviceTokenResponse = await openPassClient.deviceToken({ deviceCode: authorizeDeviceData.deviceCode });
// If the device token was returned successfully, stop polling and process the result.
if (deviceTokenResponse.status === "ok") {
// To stop polling, clear the interval.
clearInterval(pollingInterval);
// Process the response, which includes the ID token, access token, and refresh token.
// Note: Implement your own logic to process the response.
processTokenResponse(deviceTokenResponse);
} else if (deviceTokenResponse.status === "authorization_pending") {
// Authorization is pending, so continue polling.
} else if (deviceTokenResponse.status === "slow_down") {
// Slow down the polling. For example, increase the polling interval by 2 times. Note that this is not implemented in this example.
}
} catch (error) {
// Handle any errors that occur during the call to the device token function.
// Note: Implement your own error handling.
handleError(error);
}
}, pollInterval);
The following table lists the parameters:
| Parameter | Required? | Data Type | Description |
|---|---|---|---|
deviceCode |
Yes | string |
The device code which was returned from the authorizeDevice method. |
Sample responses
authorization_pending - The device token request is pending and the user has not yet authorized the device. Keep polling:
{
"status": "authorization_pending"
}
slow_down - The device token request is pending and the caller should slow down the polling frequency:
{
"status": "slow_down"
}
ok - The device token request was successful and the user has authorized themselves on another device, and the tokens are available:
{
"status": "ok",
"tokens": {
"idToken": {
"jti": "d7dd223b-c617-4d4f-9fec-a58b774c5261",
"sub": "1d20ab57-3462-406a-abaa-27d3f990084e",
"email": "test@example.com",
"aud": "6f85187cea9f4be5be1caa792581d015",
"given_name": "Gabriel Jose",
"family_name": "Garcia Marquez",
"iss": "https://auth.myopenpass.com",
"iat": 1712833688,
"exp": 1715425688
},
"rawIdToken": "...",
"accessToken": "...",
"tokenType": "Bearer",
"expiresIn": 86400
}
}
The following table lists the response fields:
| Field | Required? | Data Type | Description |
|---|---|---|---|
status |
Yes | string |
The status of the device token request, which can be one of the following values: ok, slow_down, or authorization_pending. |
tokens |
No | open pass tokens |
Required only if the status field is set to ok. The OpenPass tokens (ID token, access token) returned from a successful device token request. |
openPassClient.isAuthenticationRedirect() ⇒ boolean
Returns true if the current page was redirected to by the OpenPass authentication process after a successful or unsuccessful user sign-in.
openPassClient.handleAuthenticationRedirect() ⇒ Promise<SignInResponse>
Call this method to complete the OpenPass authentication flow in response to receiving a callback to a redirect URI from OpenPass.
Example
if (openPassClient.isAuthenticationRedirect()) {
try {
// Attempt to complete the sign-in process.
const signInResponse = await openPassClient.handleAuthenticationRedirect();
console.log(signInResponse.idToken);
console.log(signInResponse.clientState);
} catch (e) {
console.log(e);
}
}
SDK sign-in process elements
This section details the data structures and properties returned by the SDK, including the sign-in response, ID token, and error message.
OpenPassTokens
The following lists the parameters for OpenPassTokens.
| Parameter | Required? | Data Type | Description |
|---|---|---|---|
idToken |
Yes | IdToken |
The decoded ID token, which contains the user's identity details, including their email address. |
rawIdToken |
Yes | string |
The raw ID token string (JWT), which contains the user's identity details, including their email address. |
accessToken |
Yes | string |
The access token string, which can be used to do Bearer authorization against APIs. |
SignInResponse
The following lists the parameters for a successful sign-in response.
| Parameter | Required? | Data Type | Description |
|---|---|---|---|
idToken |
Yes | IdToken |
The decoded ID token, which contains the user's identity details, including their email address. |
rawIdToken |
Yes | string |
The raw ID token string (JWT), which contains the user's identity details, including their email address. |
accessToken |
Yes | string |
The access token string, which can be used to do Bearer authorization against the OpenPass API. |
originatingUri |
Yes | string |
This is the originating window URI the user was on when the authentication flow was initiated. It can be used to redirect users back to the original page they came from when handling redirect callbacks. |
clientState |
No | Record<string, string> |
The client state that was stored when initiating the authentication flow. |
IdToken
The following lists the parameters for an OpenPass ID token.
| Parameter | Required? | Data Type | Description |
|---|---|---|---|
jti |
Yes | string |
The unique identifier for the JWT. |
sub |
Yes | string |
The subject, which is the user's unique identifier. |
email |
Yes | string |
The user email address. |
given_name |
Yes | string |
The given or first name of the end user. Here are key points:
|
family_name |
Yes | string |
The surname or last name of the end user. Here are key points:
|
name |
No | string |
The full name of the end user. Here are key points:
|
iss |
Yes | string |
The token issuer. |
aud |
Yes | string |
The audience that the token is intended for, which is the client ID. |
iat |
Yes | string |
The token issue time, which is the number of seconds since the Unix epoch. |
exp |
Yes | string |
The token expiration time, which is the number of seconds since the Unix epoch. |
SdkError
The following lists the parameters for an error message.
| Parameter | Required? | Data Type | Description |
|---|---|---|---|
message |
Yes | string |
The error message. |
error |
No | string |
The error code. |
errorDescription |
No | string |
The error description. |
errorUi |
No | string |
The error URI. |
clientState |
No | string |
The client state that was stored when initiating the authentication flow. |