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 saml.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 saml.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

Install SDK

Terminal
npm i --save @descope/react-sdk
Terminal
npm i --save @descope/nextjs-sdk
Terminal
npm i --save @descope/web-js-sdk
Terminal
npm i --save @descope/vue-sdk
Terminal
npm i --save @descope/angular-sdk

Import and initialize SDK

For more information about the baseUrl, baseStaticUrl, and baseCdnUrl parameters, refer to the Base URL Configuration section.

Parameters:

  • baseUrl: Custom domain that must be configured to manage token response in cookies. This makes sure every request to our service is through your custom domain, preventing accidental domain blockages.
  • baseStaticUrl: Custom domain to override the base URL that is used to fetch static files.
  • baseCdnUrl: Custom domain to override the base URL used to load external script assets (e.g., SDKs or widgets) dynamically at runtime.
  • persistTokens: Controls whether session tokens are stored in browser localStorage. Enabled by default and accessible via getToken(). Set to false to avoid client-side storage of tokens to reduce XSS risk.
  • autoRefresh: Controls whether the session is automatically refreshed when the token is expired. Enabled by default. Set to false to disable automatic refresh of the session.
  • sessionTokenViaCookie: Controls whether the session token is stored in a cookie instead of localStorage. If persistTokens is true, then by default, the token is stored in localStorage. Set this to true to store the token in a JS cookie instead.
  • storeLastAuthenticatedUser: Determines if the last authenticated user's info is saved in localStorage. Enabled by default and accessible via getUser(). Set to false to disable this behavior.
  • keepLastAuthenticatedUserAfterLogout: Controls whether user info is kept after logout. Disabled by default. Set to true to store user data on logout.
import { AuthProvider } from '@descope/react-sdk'
import { Descope, useDescope } from '@descope/react-sdk'

const AppRoot = () => {
	return (
      <AuthProvider
          projectId="__ProjectID__"
          baseUrl="https://auth.app.example.com"
          baseCdnUrl="https://assets.app.example.com" // specify a custom CDN URL for fetching external scripts and resources
          persistTokens={true} // set to `false` to disable token storage in browser to prevent XSS
          autoRefresh={true} // set to `false` to disable automatic refresh of the session
          sessionTokenViaCookie={false} // set to `true` to store the session token in a JS cookie instead of localStorage
          storeLastAuthenticatedUser={true} // set to `false` to disable storing last user
          keepLastAuthenticatedUserAfterLogout={false} // set to `true` to persist user info after logout
        >
        <App />
      </AuthProvider>
	);
};
import { AuthProvider } from '@descope/nextjs-sdk';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <AuthProvider
      projectId="__ProjectID__"
      baseUrl="<URL>"
      baseCdnUrl="https://assets.app.example.com" // specify a custom CDN URL for fetching external scripts and resources
      persistTokens={true} // set to `false` to disable token storage in browser to prevent XSS
      autoRefresh={true} // set to `false` to disable automatic refresh of the session
      sessionTokenViaCookie={false} // set to `true` to store the session token in a JS cookie instead of localStorage
      storeLastAuthenticatedUser={true} // set to `false` to disable storing last user
      keepLastAuthenticatedUserAfterLogout={false} // set to `true` to persist user info after logout
    >
      <html lang="en">
        <body>{children}</body>
      </html>
    </AuthProvider>
  );
}
import DescopeSdk from '@descope/web-js-sdk';
try {
  const descopeSdk = DescopeSdk({
    projectId: '__ProjectID__',
    baseUrl: 'https://auth.app.example.com',
    baseCdnUrl="https://assets.app.example.com", // specify a custom CDN URL for fetching external scripts and resources
    persistTokens: true, // set to `false` to disable token storage in browser to prevent XSS
    autoRefresh: true, // set to `false` to disable automatic refresh of the session
    sessionTokenViaCookie: false, // set to `true` to store the session token in a JS cookie instead of localStorage
    storeLastAuthenticatedUser: true, // set to `false` to disable storing last user
    keepLastAuthenticatedUserAfterLogout: false, // set to `true` to persist user info after logout
  });
} catch (error) {
  // handle the error
    console.log("failed to initialize: " + error)
}
import { createApp } from "vue";
import App from "@/App.vue";
import descope, { getSdk } from "@descope/vue-sdk";

const app = createApp(App);
app.use(router);

app.use(descope, {
  projectId: '__ProjectID__',
  baseUrl: "<base url>",
  baseCdnUrl: "https://assets.app.example.com", // specify a custom CDN URL for fetching external scripts and resources
  persistTokens: true, // set to `false` to disable token storage in browser to prevent XSS
  autoRefresh: true, // set to `false` to disable automatic refresh of the session
  sessionTokenViaCookie: false, // set to `true` to store the session token in a JS cookie instead of localStorage
  storeLastAuthenticatedUser: true, // set to `false` to disable storing last user
  keepLastAuthenticatedUserAfterLogout: false, // set to `true` to persist user info after logout
});

const sdk = getSdk();
sdk?.onSessionTokenChange((newSession) => {
  // here you can implement custom logic when the session is changing
});
// app.module.ts
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { DescopeAuthModule, DescopeAuthService, descopeInterceptor } from '@descope/angular-sdk';
import { AppComponent } from './app.component';
import {
  HttpClientModule,
  provideHttpClient,
  withInterceptors
} from '@angular/common/http';
import { zip } from 'rxjs';

export function initializeApp(authService: DescopeAuthService) {
  return () => zip([authService.refreshSession(), authService.refreshUser()]);
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    DescopeAuthModule.forRoot({
      projectId: 'YOUR_PROJECT_ID',
      baseUrl: '<URL>',
      baseCdnUrl: "https://assets.app.example.com", // specify a custom CDN URL for fetching external scripts and resources
      persistTokens: true, // set to `false` to disable token storage in browser to prevent XSS
      autoRefresh: true, // set to `false` to disable automatic refresh of the session
      sessionTokenViaCookie: false, // set to `true` to store the session token in a JS cookie instead of localStorage
      storeLastAuthenticatedUser: true, // set to `false` to disable storing last user
      keepLastAuthenticatedUserAfterLogout: false // set to `true` to persist user info after logout
    })
  ],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: initializeApp,
      deps: [DescopeAuthService],
      multi: true
    },
    provideHttpClient(withInterceptors([descopeInterceptor]))
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

OIDC Configuration

If you're using our SDK as an OIDC client with our Federated Apps, you can initialize the oidcConfig parameter with the following items:

  • applicationId: This is the application id, that can be found within the settings of your Federated Application
  • redirectUri: This is the url that will be redirected to if the user is unauthenticated. The default redirect URI will be used if not provided.
  • scope: This is a string of the scopes that the OIDC client will request from Descope. This should be one string value with spaces in between each scope. The default scopes are: 'openid email roles descope.custom_claims offline_access'

Step 1: Start SSO

When the user clicks sign in with SSO, call saml.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.saml.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.saml.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.saml.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 saml.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.saml.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.saml.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.saml.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>

Step 3: Validate the Session

The last step is validating the user's session. Descope handles session management for you, including configurable timeouts and logout. For the details and sample code, see client session validation.

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