Aller au contenu principal
For our new friends:

Logto is an Auth0 alternative designed for modern apps and SaaS products. It offers both Cloud and Open-source services to help you quickly launch your identity and management (IAM) system. Enjoy authentication, authorization, and multi-tenant management all in one.

We recommend starting with a free development tenant on Logto Cloud. This allows you to explore all the features easily.

In this article, we will go through the steps to quickly build the SAML sign-in experience (user authentication) with Chrome extension and Logto.

Prerequisites

Create an application in Logto

Logto is based on OpenID Connect (OIDC) authentication and OAuth 2.0 authorization. It supports federated identity management across multiple applications, commonly called Single Sign-On (SSO).

To create your Single page app application, simply follow these steps:

  1. Open the Logto Console. In the "Get started" section, click the "View all" link to open the application frameworks list. Alternatively, you can navigate to Logto Console > Applications, and click the "Create application" button. Get started
  2. In the opening modal, click the "Single page app" section or filter all the available "Single page app" frameworks using the quick filter checkboxes on the left. Click the "Chrome extension" framework card to start creating your application. Frameworks
  3. Enter the application name, e.g., "Bookstore," and click "Create application".

🎉 Ta-da! You just created your first application in Logto. You'll see a congrats page which includes a detailed integration guide. Follow the guide to see what the experience will be in your application.

Integrate Chrome extension with Logto

astuce:
  • The following demonstration was tested on Chrome v123.0.6312.87 (arm64). Other versions should also work, as long as they support the chrome APIs used in the SDK.
  • The sample project is available on our GitHub repository.

Installation

npm i @logto/chrome-extension

The authentication flow

Assuming you put a "Sign in" button in your Chrome extension's popup, the authentication flow will look like this:

For other interactive pages in your extension, you just need to replace the Extension popup participant with the page's name. In this tutorial, we will focus on the popup page.

Regarding redirect-based sign-in

  1. This authentication process follows the OpenID Connect (OIDC) protocol, and Logto enforces strict security measures to protect user sign-in.
  2. If you have multiple apps, you can use the same identity provider (Logto). Once the user signs in to one app, Logto will automatically complete the sign-in process when the user accesses another app.

To learn more about the rationale and benefits of redirect-based sign-in, see Logto sign-in experience explained.

Update the manifest.json

Logto SDK requires the following permissions in the manifest.json:

manifest.json
{
"permissions": ["identity", "storage"],
"host_permissions": ["https://*.logto.app/*"]
}
  • permissions.identity: Required for the Chrome Identity API, which is used to sign in and sign out.
  • permissions.storage: Required for storing the user's session.
  • host_permissions: Required for the Logto SDK to communicate with the Logto APIs.
remarque:

If you are using a custom domain on Logto Cloud, you need to update the host_permissions to match your domain.

Set up a background script (service worker)

In your Chrome extension's background script, initialize the Logto SDK:

service-worker.js
import LogtoClient from '@logto/chrome-extension';

export const logtoClient = new LogtoClient({
endpoint: '<your-logto-endpoint>'
appId: '<your-logto-app-id>',
});

Replace <your-logto-endpoint> and <your-logto-app-id> with the actual values. You can find these values in the application page you just created in the Logto Console.

If you don't have a background script, you can follow the official guide to create one.

info:

Why do we need a background script?

Normal extension pages like the popup or options page can't run in the background, and they have the possibility to be closed during the authentication process. A background script ensures the authentication process can be properly handled.

Then, we need to listen to the message from other extension pages and handle the authentication process:

service-worker.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
// In the below code, since we return `true` for each action, we need to call `sendResponse`
// to notify the sender. You can also handle errors here, or use other ways to notify the sender.

if (message.action === 'signIn') {
const redirectUri = chrome.identity.getRedirectURL('/callback');
logtoClient.signIn(redirectUri).finally(sendResponse);
return true;
}

if (message.action === 'signOut') {
const redirectUri = chrome.identity.getRedirectURL();
logtoClient.signOut(redirectUri).finally(sendResponse);
return true;
}

return false;
});

You may notice there are two redirect URIs used in the code above. They are both created by chrome.identity.getRedirectURL, which is a built-in Chrome API to generate a redirect URL for auth flows. The two URIs will be:

  • https://<extension-id>.chromiumapp.org/callback for sign-in.
  • https://<extension-id>.chromiumapp.org/ for sign-out.

Note that these URIs are not accessible, and they are only used for Chrome to trigger specific actions for the authentication process.

Update Logto application settings

Now we need to update the Logto application settings to allow the redirect URIs we just created.

  1. Go to the application page in the Logto Console.
  2. In the "Redirect URIs" section, add the URI: https://<extension-id>.chromiumapp.org/callback.
  3. In the "Post sign-out redirect URIs" section, add the URI: https://<extension-id>.chromiumapp.org/.
  4. In the "CORS allowed origins" section, add the URI: chrome-extension://<extension-id>. The SDK in Chrome extension will use this origin to communicate with the Logto APIs.
  5. Click on Save changes.

Remember to replace <extension-id> with your actual extension ID. You can find the extension ID in the chrome://extensions page.

Add sign-in and sign-out buttons to the popup

We're almost there! Let's add the sign-in and sign-out buttons and other necessary logic to the popup page.

In the popup.html file:

popup.html
<button id="sign-in">Sign in</button> <button id="sign-out">Sign out</button>

In the popup.js file (assuming popup.js is included in the popup.html):

popup.js
document.getElementById('sign-in').addEventListener('click', async () => {
await chrome.runtime.sendMessage({ action: 'signIn' });
// Sign-in completed (or failed), you can update the UI here.
});

document.getElementById('sign-out').addEventListener('click', async () => {
await chrome.runtime.sendMessage({ action: 'signOut' });
// Sign-out completed (or failed), you can update the UI here.
});

Checkpoint: Test the authentication flow

Now you can test the authentication flow in your Chrome extension:

  1. Open the extension popup.
  2. Click on the "Sign in" button.
  3. You will be redirected to the Logto sign-in page.
  4. Sign in with your Logto account.
  5. You will be redirected back to the Chrome.

Check authentication state

Since Chrome provide unified storage APIs, rather than the sign-in and sign-out flow, all other Logto SDK methods can be used in the popup page directly.

In your popup.js, you can reuse the LogtoClient instance created in the background script, or create a new one with the same configuration:

popup.js
import LogtoClient from '@logto/chrome-extension';

const logtoClient = new LogtoClient({
endpoint: '<your-logto-endpoint>'
appId: '<your-logto-app-id>',
});

// Or reuse the logtoClient instance created in the background script
import { logtoClient } from './service-worker.js';

Then you can create a function to load the authentication state and user's profile:

popup.js
const loadAuthenticationState = async () => {
const isAuthenticated = await logtoClient.isAuthenticated();
// Update the UI based on the authentication state

if (isAuthenticated) {
const user = await logtoClient.getIdTokenClaims(); // { sub: '...', email: '...', ... }
// Update the UI with the user's profile
}
};

You can also combine the loadAuthenticationState function with the sign-in and sign-out logic:

popup.js
document.getElementById('sign-in').addEventListener('click', async () => {
await chrome.runtime.sendMessage({ action: 'signIn' });
await loadAuthenticationState();
});

document.getElementById('sign-out').addEventListener('click', async () => {
await chrome.runtime.sendMessage({ action: 'signOut' });
await loadAuthenticationState();
});

Here's an example of the popup page with the authentication state:

Popup page

Other considerations

  • Service worker bundling: If you use a bundler like Webpack or Rollup, you need to explicitly set the target to browser or similar to avoid unnecessary bundling of Node.js modules.
  • Module resolution: Logto Chrome extension SDK is an ESM-only module.

See our sample project for a complete example with TypeScript, Rollup, and other configurations.

Add SAML connector

To enable quick sign-in and improve user conversion, connect with Chrome extension as an identity provider. The Logto social connector helps you establish this connection in minutes by allowing several parameter inputs.

To add a social connector, simply follow these steps:

  1. Navigate to Console > Connectors > Social Connectors.
  2. Click "Add social connector" and select "SAML".
  3. Follow the README guide and complete required fields and customize settings.
Connector tab
remarque:

If you are following the in-place Connector guide, you can skip the next section.

Set up Standard SAML app

Create social IdP's account and register SAML application (IdP)

Let's go through configurations of SAML connector.

Before we kicking off, you can go to a social identity provider which supports SAML protocol and create your own account. Okta, OneLogin, Salesforce and some other platforms support authentication based on SAML protocol.

If your IdP mandate the encryption of SAML assertion and receiving of signed authentication requests, you should generate your private key and corresponding certificate using RSA algorithm. Keep the private key for your SP use and upload the certificate to IdP.

You also need to configure the ACS (Assertion Consumer Service) URL as ${your_logto_origin}/api/authn/saml/${connector_id} to handle IdP's SAML assertion. Where you can find your connectorId at SAML connector's details page in Logto's Admin Console.

remarque:

Per current Logto's design, we only support Redirect-binding for sending authentication request and POST-binding for receiving SAML assertion. Although this sounds not cool, but we believe that the current design can handle most of your use cases. If you have any problems, feel free to reach out!

Configure SAML connector (SP)

In this section, we will introduce each attribute in detail.

entityID Required

entityID (i.e. issuer) is Entity identifier. It is used to identify your entity (SAML SP entity), and match the equivalence in each SAML request/response.

signInEndpoint Required

The IdP's endpoint that you send SAML authentication requests to. Usually, you can find this value in IdP details page (i.e. IdP's SSO URL or Login URL).

x509Certificate Required

The x509 certificate generated from IdPs private key, IdP is expected to have this value available.

The content of the certificate comes with -----BEGIN CERTIFICATE----- header and -----END CERTIFICATE----- tail.

idpMetadataXml Required

The field is used to place contents from your IdP metadata XML file.

remarque:

The XML parser we are using does not support customized namespace. If the IdP metadata comes with namespace, you should manually remove them. For namespace of XML file, see reference.

assertionConsumerServiceUrl Required

The assertion consumer service (ACS) URL is the SP's endpoint to receive IdP's SAML Assertion POST requests. As we mentioned in previous part, it is usually configured at IdP settings but some IdP get this value from SAML authentication requests, we hence also add this value as a REQUIRED field. It's value should look like ${your_logto_origin}/api/authn/saml/${connector_id}.

signAuthnRequest

The boolean value that controls whether SAML authentication request should be signed, whose default value is false.

encryptAssertion

encryptAssertion is a boolean value that indicates if IdP will encrypt SAML assertion, with default value false.

remarque:

The signAuthnRequest and encryptAssertion attributes should align with corresponding parameters of IdP setting, otherwise error will be thrown to show that configuration does not match. All SAML responses need to be signed.

requestSignatureAlgorithm

This should be aligned with the signature algorithms of IdP so that Logto can verify the signature of the SAML assertion. Its value should be either http://www.w3.org/2000/09/xmldsig#rsa-sha1, http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 or http://www.w3.org/2001/04/xmldsig-more#rsa-sha512 and the default value is http://www.w3.org/2001/04/xmldsig-more#rsa-sha256.

messageSigningOrder

messageSigningOrder indicates the signing and encrypting order of IdP, it's value should be either sign-then-encrypt or encrypt-then-sign and the default value is sign-then-encrypt.

privateKey and privateKeyPass

privateKey is an OPTIONAL value and is required when signAuthnRequest is true.

privateKeyPass is the password you've set when creating privateKey, required when necessary.

If signAuthnRequest is true, the corresponding certificate generated from privateKey is required by IdP for checking the signature.

encPrivateKey and encPrivateKeyPass

encPrivateKey is an OPTIONAL value and is required when encryptAssertion is true.

encPrivateKeyPass is the password you've set when creating encPrivateKey, required when necessary.

If encryptAssertion is true, the corresponding certificate generated from encPrivateKey is required by IdP for encrypting SAML assertion.

remarque:

For keys and certificates generation, openssl is a wonderful tool. Here is sample command line that might be helpful:

openssl genrsa -passout pass:${privateKeyPassword} -out ${encryptPrivateKeyFilename}.pem 4096
openssl req -new -x509 -key ${encryptPrivateKeyFilename}.pem -out ${encryptionCertificateFilename}.cer -days 3650

privateKey and encPrivateKey files are enforced to be encoded in pkcs1 scheme as pem string, which means the private key files should start with -----BEGIN RSA PRIVATE KEY----- and end with -----END RSA PRIVATE KEY-----.

nameIDFormat

nameIDFormat is an OPTIONAL attribute that declares the name id format that would respond. The value can be among urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified, urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress, urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName, urn:oasis:names:tc:SAML:2.0:nameid-format:persistent and urn:oasis:names:tc:SAML:2.0:nameid-format:transient, and the default value is urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified.

timeout

timeout is the time tolerance for time validation, since the time between your SP entity and IdP entity could be different and network connection may also bring some delay. The unit is in millisecond, and the default value is 5000 (i.e. 5s).

profileMap

Logto also provide a profileMap field that users can customize the mapping from the social vendors' profiles which are usually not standard. Each profileMap keys is Logto's standard user profile field name and corresponding value should be social profiles field name. In current stage, Logto only concern 'id', 'name', 'avatar', 'email' and 'phone' from social profile, only 'id' is REQUIRED and others are optional fields.

Config types

NameTypeRequiredDefault Value
signInEndpointstringtrue
x509certificatestringtrue
idpMetadataXmlstringtrue
entityIDstringtrue
assertionConsumerServiceUrlstringtrue
messageSigningOrderencrypt-then-sign | sign-then-encryptfalsesign-then-encrypt
requestSignatureAlgorithmhttp://www.w3.org/2000/09/xmldsig#rsa-sha1 | http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 | http://www.w3.org/2001/04/xmldsig-more#rsa-sha512falsehttp://www.w3.org/2001/04/xmldsig-more#rsa-sha256
signAuthnRequestbooleanfalsefalse
encryptAssertionbooleanfalsefalse
privateKeystringfalse
privateKeyPassstringfalse
nameIDFormaturn:oasis:names:tc:SAML:1.1:nameid-format:unspecified | urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress | urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName | urn:oasis:names:tc:SAML:2.0:nameid-format:persistent | urn:oasis:names:tc:SAML:2.0:nameid-format:transientfalseurn:oasis:names:tc:SAML:1.1:nameid-format:unspecified
timeoutnumberfalse5000
profileMapProfileMapfalse
ProfileMap fieldsTypeRequiredDefault value
idstringfalseid
namestringfalsename
avatarstringfalseavatar
emailstringfalseemail
phonestringfalsephone

Reference

Save your configuration

Double check you have filled out necessary values in the Logto connector configuration area. Click "Save and Done" (or "Save changes") and the SAML connector should be available now.

Enable SAML connector in Sign-in Experience

Once you create a social connector successfully, you can enable it as a "Continue with SAML" button in Sign-in Experience.

  1. Navigate to Console > Sign-in experience > Sign-up and sign-in.
  2. (Optional) Choose "Not applicable" for sign-up identifier if you need social login only.
  3. Add configured SAML connector to the "Social sign-in" section.
Sign-in Experience tab

Testing and Validation

Return to your Chrome extension app. You should now be able to sign in with SAML. Enjoy!

Further readings

End-user flows: Logto provides a out-of-the-box authentication flows including MFA and enterprise SSO, along with powerful APIs for flexible implementation of account settings, security verification, and multi-tenant experience.

Authorization: Authorization defines the actions a user can do or resources they can access after being authenticated. Explore how to protect your API for native and single-page applications and implement Role-based Access Control (RBAC).

Organizations: Particularly effective in multi-tenant SaaS and B2B apps, the organization feature enable tenant creation, member management, organization-level RBAC, and just-in-time-provisioning.

Customer IAM series Our serial blog posts about Customer (or Consumer) Identity and Access Management, from 101 to advanced topics and beyond.