Single Sign-On (SSO) with Client SDKs

Use the client SDK when the SSO handshake has to run in the browser. This usually means a single-page app with no backend to exchange the code.

If you do have a server, SSO with Backend SDKs is usually the better fit, because it keeps the code exchange off the client. If you want Descope to own login and sessions instead, start with the Flows quickstart.

SSO is configured per tenant, so each customer's SAML or OIDC connection can point at a different identity provider. See tenant management for how to set that up.

Note

Before the code below will work, enable SSO at the project level and configure a SAML or OIDC connection for at least one tenant. For the full walkthrough, see Getting Started with SSO, or test without your own IdP.

How the Flow Works

With the client SDKs, the SDK running in the user's browser drives the login. There are three steps.

  1. Start SSO. You call sso.start, and the SDK redirects the browser to the tenant's identity provider. After the user authenticates, the browser comes back to your redirectURL with a one-time code.
  2. Exchange the code. You call sso.exchange with that code. The SDK gets the user's session tokens back and stores them for you.
  3. Validate the session. The SDK keeps the session fresh with auto-refresh and validates it on later requests.

The diagram below shows who talks to whom at each step. Descope acts as the SAML/OIDC service provider toward the identity provider, so you never build the federation yourself.

UserYour AppDescopeIdentity Providersign in with SSOsaml.start(tenant)authorization URLredirect to IdPauthenticateredirect with codereturn with codesaml.exchange(code)session tokensSDK stores & refreshes the session

The Descope client SDK runs start and exchange in the browser, stores the session, and refreshes it for you.

Client SDK

For information on how to install and initialize the Descope Client SDK, please refer to the Client SDK Installation Guide.

Step 1: Start SSO

When the user clicks sign in with SSO, call sso.start. The SDK redirects the browser straight to the tenant's identity provider login screen.

// Args:
//   tenant_name_id_or_email: ID of the tenant that the user is authenticating to. The tenant ID is assigned to tenant at the time of creation.
const tenant_name_id_or_email = "xxxx"
//   redirectURL: URL to return to after successful authentication with the SSO identity provider. You need to implement this page to access the token and finish oauth process (token exchange). The token arrives as a query parameter named 'code'.
const redirectURL = "https://auth.company.com/token_exchange"
//    loginOptions (LoginOptions): this allows you to configure behavior during the authentication process.
const loginOptions = {
      "stepup": false,
      "mfa": false,
      "customClaims": {"claim": "Value1"},
      "templateOptions": {"option": "Value1"}
    }
//    refreshToken (optional): the user's current refresh token in the event of stepup/mfa

const descopeSdk = useDescope();
const resp = await descopeSdk.sso.start(tenant_name_id_or_email, redirectURL, loginOptions);
if (!resp.ok) {
  console.log("Failed to start sso auth")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  const url = resp.data.url
  console.log("Successfully started sso auth. URL: " + url)
}
// Args:
//   tenant_name_id_or_email: ID of the tenant that the user is authenticating to. The tenant ID is assigned to tenant at the time of creation.
const tenant_name_id_or_email = "xxxx"
//   redirectURL: URL to return to after successful authentication with the SSO identity provider. You need to implement this page to access the token and finish oauth process (token exchange). The token arrives as a query parameter named 'code'.
const redirectURL = "https://auth.company.com/token_exchange"
//    loginOptions (LoginOptions): this allows you to configure behavior during the authentication process.
const loginOptions = {
      "stepup": false,
      "mfa": false,
      "customClaims": {"claim": "Value1"},
      "templateOptions": {"option": "Value1"}
    }
//    refreshToken (optional): the user's current refresh token in the event of stepup/mfa

const resp = await descopeSdk.sso.start(tenant_name_id_or_email, redirectURL, loginOptions);
if (!resp.ok) {
  console.log("Failed to start sso auth")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  const url = resp.data.url
  console.log("Successfully started sso auth. URL: " + url)
}
<script>
  let descopeSdk = Descope({projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });

  async function startSSO() {
    // Args:
    //   tenant_name_id_or_email: ID of the tenant that the user is authenticating to. The tenant ID is assigned to tenant at the time of creation.
    const tenant_name_id_or_email = document.getElementById("email").value
    //   redirectURL: URL to return to after successful authentication with the SSO identity provider. You need to implement this page to access the token and finish oauth process (token exchange). The token arrives as a query parameter named 'code'.
    const redirectURL = "https://auth.company.com/token_exchange"
    //    loginOptions (LoginOptions): this allows you to configure behavior during the authentication process.
    const loginOptions = {
          "stepup": false,
          "mfa": false,
          "customClaims": {"claim": "Value1"},
          "templateOptions": {"option": "Value1"}
        }
    //    refreshToken (optional): the user's current refresh token in the event of stepup/mfa

    const resp = await descopeSdk.sso.start(tenant_name_id_or_email, redirectURL, loginOptions);
    if (!resp.ok) {
      window.alert("Failed to start SSO\nStatus Code: " + resp.code
        + "\nError Code: " + resp.error.errorCode + "\nError Description: " + resp.error.errorDescription + "\nError Message: " + resp.error.errorMessage)
    }
    else {
      console.log("Successfully Started SSO flow")
      window.location.replace(resp.data.url)
    }
  }
</script>

Step 2: Exchange the Code

After the user authenticates, the IdP sends them back to the redirectURL you passed to sso.start, with the code in the query string. Pull the code off the URL and exchange it as shown below.

// Args:
//   code: code extracted from the url after user is redirected to redirectURL. The code is in the url as a query parameter "code" of the page.
const code = "xxxxx"

const descopeSdk = useDescope();
const resp = await descopeSdk.sso.exchange(code);
if (!resp.ok) {
  console.log("Failed to verify sso code")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully verified sso code.")
}
// Args:
//   code: code extracted from the url after user is redirected to redirectURL. The code is in the url as a query parameter "code" of the page.
const code = "xxxxx"

const resp = await descopeSdk.sso.exchange(code);
if (!resp.ok) {
  console.log("Failed to verify sso code")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully verified sso code.")
}
<script>
  const queryString = window.location.search;
  const params = new URLSearchParams(queryString)
  const authURLCode = params.get("code")
  console.log(authURLCode)
  let descopeSdk = Descope({projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });

  ssoFinishExchange(authURLCode)

  async function ssoFinishExchange(thisCode) {
    // Args:
    //   code: code extracted from the url after user is redirected to redirectURL. The code is in the url as a query parameter "code" of the page.
    const code = thisCode

    const resp = await descopeSdk.sso.exchange(code);
    if (!resp.ok) {
      window.alert("Failed to finish SSO\nStatus Code: " + resp.code
        + "\nError Code: " + resp.error.errorCode + "\nError Description: " + resp.error.errorDescription + "\nError Message: " + resp.error.errorMessage)
    }
    else {
      console.log("Successfully finished SSO")
      window.location.replace("../loggedIn.html?userId=" + encodeURIComponent(resp.data.user.loginIds) + "&sessionJwt=" + resp.data.sessionJwt)
    }
  }
</script>

Checkpoint

Your application is now integrated with Descope. Please test with sign-up or sign-in use case.

Need help?
Was this helpful?

On this page