Skip to main contentArrow Right
Banner labeled "Developer Guide" showing an icon of a cloud with a padlock, a plus sign, and the Descope logo, above the title "Add SSO to Homegrown Auth."

Table of Contents

Summarize with AI

Don't have the time to read the entire post? Our human writers will be sad, but we understand. Summarize the post with your preferred LLM here instead.

When you first build an authentication system, simplicity is the goal. An email-and-password login gets users signed in quickly and lets your team focus on product features. But as your app starts to attract larger customers, the conversation changes.

  • Protocol complexity: SAML, OIDC, OAuth—they all sound similar but work very differently.

  • Full SSO lifecycle: Handling metadata, login hints, domain routing, logout, user attributes, etc.

  • Enterprise requirements: Customers don’t just want SSO; they want to integrate their own IdPs (like Microsoft Entra ID) securely, with full admin control over authentication and access policies.

Trying to build all of this from scratch is not only time-consuming, it also introduces security risks if not done right. Using a platform like Descope is the easiest way to extend a homegrown system with SSO and multi-tenancy, without rebuilding everything from the ground up.

In this blog, we’ll walk through how to add SSO to a homegrown authentication system using Descope, with Microsoft Entra ID (formerly Azure AD) as the provider. But first, let’s address why SSO can be such a challenge to implement within a custom-built auth system.

Why adding SSO to homegrown auth is so hard

SSO is a core expectation of enterprise B2B customers. But if you’re working with a custom-built system teeming with tech debt, extending a homegrown authentication system to support enterprise SSO is rarely straightforward. You’re not simply adding a SAML or OIDC endpoint, but are instead managing the entire lifecycle:

  • Tenant discovery: Determining which IdP to route a user to, usually based on their email domain.

  • Certificates and metadata: Exchanging, configuring, and rotating SAML certificates across tenants.

  • Custom endpoints: Setting up login, logout, and callback URLs for each enterprise customer.

  • Ongoing maintenance: Handling unique customer requirements, configuration drift, and constant updates as IdPs evolve.

Each new enterprise deal often brings its own quirks, creating a steady stream of custom integrations and ongoing support work. For a product team, this quickly turns into a major distraction from core development.

Adding SSO to homegrown authentication with Descope

This is where Descope comes in. Instead of rebuilding your authentication system from the ground up, you can extend it with enterprise-ready SSO support out of the box. Descope handles the protocol complexity, tenant routing, and IdP integrations, while still letting you keep your existing login system intact. You get the best of both worlds:

  • Users log in seamlessly with their company credentials.

  • Enterprises securely connect their own IdPs and let their admins control access.

  • Your team avoids the heavy lift of building and maintaining these flows in-house.

Prerequisites

Before continuing, ensure you have the following:

Configuring Descope as a SAML application in Microsoft Entra ID

Go to the Microsoft Azure / Entra ID portal and add a new enterprise application:

  • Click + Add Enterprise Application

  • Choose Create your own Application and give it a name

  • Select Integrate any other application you don’t find in the gallery

  • Click Create

Set up single sign-on:

  • Once the application is created, go to the single sign-on in the left panel. 

  • Choose the SAML option.

Microsoft Entra ID enterprise application page titled "SSO Augmentation | SAML-based Sign-on." In the left menu, under Manage, "Single sign-on" is selected; the other menu items are blurred. The main panel is headed "Set up Single Sign-On with SAML" and reads: "An SSO implementation based on federation protocols improves security, reliability, and end user experiences and is easier to implement. Choose SAML single sign-on whenever possible for existing applications that do not use OpenID Connect or OAuth. Learn more." followed by "Read the configuration guide for help integrating SSO Augmentation." Step 1, "Basic SAML Configuration," has an Edit link and lists Identifier (Entity ID), Reply URL (Assertion Consumer Service URL), Sign on URL, Relay State (Optional), and Logout Url (Optional), with blurred values. Step 2, "Attributes & Claims," has an Edit link and lists givenname, surname, emailaddress, name, and Unique User Identifier, with blurred values.
Fig: Setting up single sign-on

Configure SAML settings:

  • In the basic SAML configuration section, enter the following:

    • Identifier (Entity ID): Copy this from the Descope Console under Tenant Settings > Authentication Methods > SSO > SAML > SSO Configuration 

    • Reply URL (Assertion Consumer Service URL/ Descope ACS URL): Also found in the same SAML settings section in Descope

Descope Console tenant settings for a tenant named Azure, with the breadcrumb "sso-homegrown / Tenants / Azure" and a "Back to Tenants" link. The left menu lists Authentication Methods (selected) and Authorization under Build, and Tenant Settings under Settings. A second menu lists SSO (selected) and Passwords. In the SSO settings panel, most fields are dimmed and two are highlighted: "Descope Entity ID (not required by all providers)" with a value beginning "P2x0SjsFN8WlDuviSL8SJIlH9CqJ-T2x6YwNN," and "Descope ACS URL" with a value beginning "https://api.descope.com/v1/auth/saml/acs?p." Each has a copy icon. Dimmed fields above include "Post Authentication Redirect URL" with the redirect URL http://localhost:3000/api/auth/callback and a "Service Provider" section with a Descope metadata URL and a "Download Metadata (XML)" link; a "Subject NameID Format" field set to None is below.
Fig: Obtaining the entity ID and ACS URL from Descope

Click Save once you’ve filled in the required fields.

Project and SSO configuration in Descope

Log in to the Descope Console and create a new project if you don’t already have one.

Create a Tenant:

  • Go to the Tenants section

  • Create a new tenant for your organization or customer

  • Copy the Tenant ID—you’ll need it later

Descope Console Tenants page with two areas highlighted and the rest of the screen blurred: the "Tenants" item in the left navigation under Manage, and the "+ Tenant" button at the top right of the tenant table. The blurred page behind shows a "Tenants" heading, "Tenants" and "Custom Attributes" tabs, a search box, and a table with columns for Name, ID, SSO Domains, Created Time, SSO, and Status. The table lists two tenants, "Azure" with SSO set to saml and "test-tenant" with SSO set to none, both marked Active, with "Total Rows: 2" at the bottom.
Fig: Creating a tenant in the Descope console

Configure SAML as the authentication protocol:

  • Go to Tenant Settings > Authentication Methods > SSO

  • Under Authentication Protocol, select SAML

Descope Console settings for a tenant named Azure, with the breadcrumb "sso-homegrown / Tenants / Azure." In the left navigation, "Authentication Methods" under Build is highlighted, and "SSO" is selected in the methods list above "Passwords." The highlighted SSO panel reads "Use SAML or OIDC to access multiple web applications with one set of login credentials. Multiple SSO Configuration is supported," followed by a "Learn More" link. An "SSO Configuration" dropdown is set to "Default." Under "Authentication Protocol," there are three radio options, None, SAML, and OIDC, with SAML selected. Blurred below is a "Tenant Details" section with "SSO Domains" and "JIT Provisioning" settings.
Fig: Setting up single sign-on

Update SSO mapping:

  • Still in the SAML configuration screen, find the SSO Mapping section.

  • Add the appropriate attributes and claims to match what’s configured in your Entra ID Portal (e.g., email, firstName, lastName, groups, etc.)

Descope Console SSO settings for the Azure tenant, with the "SSO Mapping" section highlighted. Under "User Attribute Mapping," the text reads "Map the following user attributes from the Identity Provider (IdP) to Descope, affecting both JIT and SCIM." Four rows each pair an "IdP user value" field with a "Descope user attribute" dropdown, joined by the words "map to." Every IdP user value begins with "http://schemas.xmlsoap.org/ws/2005/" and is cut off by the field width. The four Descope user attributes are Display Name, Email, Given Name, and Family Name. Each row has a remove button, and an "Add user attribute mapping" link sits below the rows. A blurred "Group Attribute Mapping" section with a "Groups attribute name" field follows.
Fig: Updating the User Attribute mapping in the Descope console

Set the post-authentication redirect URL

  • Back in the Descope console, go to Authentication Methods > SSO

  • Set the post authentication redirect URL to the page you want users to land on after logging in.

The setup is straightforward, and with the SSO setup suite, you can even share a link that lets your customer’s tenant admins configure their own SSO connection.

Descope Console Authentication Methods page with "Authentication Methods" highlighted under Build in the left navigation and "SSO" highlighted in the list of methods. The other entries in the list are blurred and cover these methods: one-time password, magic link, Enchanted Link, embedded link, social login (OAuth / OIDC), nOTP (WhatsApp), passkeys (WebAuthn), authenticator apps (TOTP), passwords, and security questions. In the SSO settings, the highlighted "General" section has a toggle turned on labeled "Convert existing user to SSO-only after successful SSO login." Below it, the text reads "The URL the end user is redirected to after a successful authentication. If one is specified in tenant level settings or SDK/API call, they will override this value." The "Post Authentication Redirect URL" field contains "http://localhost:3000/api/auth/callback." Blurred settings below include "Mandatory User Attributes," "Mappable FGA Types," and "SSO Setup Suite Settings."
Fig: Configuring the post-authentication redirect URL

Validate credentials

This endpoint demonstrates how you can adapt an existing login API route to support SSO with Microsoft Entra (or any other IdP) using Descope.

In a traditional setup, your login API receives the user’s email and password, verifies those credentials, and establishes a session. When introducing SSO, the flow changes: instead of validating a password, you only take the user’s email, determine which tenant (and IdP) they belong to, and return a redirect URL that initiates the SSO login with their company’s identity provider.

Here’s what’s happening step by step:

Client request: The client sends the user’s email to /api/auth/login.

Backend Processing: The backend calls getSamlRedirectUrl(email), which:

  • Identifies the correct tenant based on the email domain. This is sometimes referred to as Home Realm Discovery, which is natively supported by Descope.

  • Uses the Descope SDK (saml.start) to generate a redirect URL for that tenant’s IdP.

  • Appends a login_hint parameter so Microsoft Entra can pre-fill the user’s email on the login page.

API response: The backend returns the redirect URL to the client.

Client redirect: The client uses that URL to send the user directly into their organization’s Microsoft Entra login page.

Why does this approach work? From a security standpoint, the backend controls tenant and IdP selection, meaning the client cannot spoof or choose an IdP on its own. Meanwhile, different email domains can map to different tenants and IdPs, making it easy to support multiple organizations in one app. Lastly, with login_hint, users don’t need to re-enter their email, making the SSO flow smoother and faster.

app.post('/api/auth/login', async (req: Request, res: Response) => {
  const { email } = req.body;
  try {
    const redirectUrl = await getSamlRedirectUrl(email);
    console.log('Sending redirect URL:', redirectUrl);
    res.json({ redirectUrl });
  } catch (error) {
    console.error('Login error:', error);
    res.status(500).json({ message: 'Error getting redirect URL' });
  }
});

Get the SAML redirect URL

This function uses descopeClient.saml.start() to initiate the SSO login and appends a login_hint to streamline the Microsoft Entra experience by pre-filling the email.

const getSamlRedirectUrl = async (userEmail: string) => {
    const tenantId = process.env.DESCOPE_TENANT_ID;
    const projectId = process.env.DESCOPE_PROJECT_ID;
    const response = await descopeClient.saml.start(tenantId);
    return response.data.url + `&login_hint=${userEmail}`;
};

Handle the callback

This endpoint receives the callback from Descope after the user authenticates with the identity provider (Microsoft Entra). It extracts the authorization code from the query parameters.

app.get('/api/auth/callback', async (req: Request, res: Response) => {
  const { code } = req.query;

  if (!code) {
      console.error('No code provided');
      return res.status(400).json({ message: 'No code provided' });
  }

// Proceed to token exchange...
};

Exchanging the code for a session

Once we have the authorization code, we use Descope’s SDK to exchange it for a session token. This token represents the user’s authenticated session.

const sessionResponse = await descopeClient.saml.exchange(code as string);

if (!sessionResponse.data?.refreshJwt) {
  return res.status(401).json({ message: 'No session token received' });
}

We then validate this session token to confirm its authenticity.

const sessionValidation = await descopeClient.validateSession(sessionResponse.data.refreshJwt);

Protect routes with middleware

In this example, we’re issuing a custom JWT after validating Descope’s session. The key idea here is that once Descope confirms the user’s identity through SSO, you can integrate that result into your existing session flow, whatever that may be. This way, you continue managing sessions exactly as before, while still gaining SSO support.

This token can then be used to authorize access to protected routes, just like any other token-based authentication flow.

app.get('/api/protected', authenticateToken, (req: AuthenticatedRequest, res: Response) => {
  res.json({ message: 'This is a protected route', user: req.user });
});

What’s going on under the hood

Sequence diagram titled "SSO Authentication Flow" with four participants: User, Backend, Descope, and Entra. The steps run in this order. The user enters an email address. The user sends "POST /api/auth/login {email}" to the backend. A note reads "Backend generates SAML redirect URL via Descope." The backend calls "descopeClient.saml.start(tenantId)" on Descope. Descope returns "SAML redirect URL {redirectUrl}" to the user. The user follows the step "Navigate to Entra ID page and sign in with credentials," which goes to Entra. A note reads "Entra receives email as login hint." Entra performs "Validate credentials." Entra sends "Redirect to /api/auth/callback with SAML response" back to the user. The user sends "GET /api/auth/callback?code={auth_code}." A note reads "Backend exchanges SAML response for session." The backend calls "descopeClient.saml.exchange(code)" on Descope. Descope responds to the backend: "Code is verified and a token is returned." A backend note reads "Generate custom JWT token + Sign JWT with user info." Finally, a note on the user side reads "Display protected content."
Fig: Diagram illustrating adding SSO to homegrown auth

Here’s how the SSO authentication flow works, step by step:

  • Enter email address: The user starts by entering their email address, which is sent to the backend in a POST /api/auth/login {email} request.

  • Generate redirect URL: The backend calls descopeClient.saml.start(tenantId) to generate a SAML redirect URL through Descope.

  • Receive redirect URL: Descope responds with the redirect URL, which the backend returns to the user.

  • Redirect to identity provider: The user is redirected to the Entra ID sign-in page, and their email address is passed along as a login hint.

  • Sign in with credentials: On the Entra page, the user enters their credentials, and Entra validates them.

  • Return with SAML response: After successful validation, Entra redirects the user back to the backend at /api/auth/callback along with the SAML response.

  • Handle callback: The backend processes this redirect as a GET /api/auth/callback?code={auth_code} request.

  • Exchange for session: The backend calls descopeClient.saml.exchange(code) to exchange the SAML response for a session.

  • Verify and return token: Descope verifies the code and returns a valid token to the backend.

  • Generate custom JWT: The backend creates a custom JWT token, embedding the user’s information, and signs it securely.

  • Access granted: With the JWT in place, the user is successfully authenticated and can now view the protected content.

Simplifying SSO for homegrown auth with Descope

Adding SSO to a homegrown authentication system doesn’t have to mean a full rebuild. With Descope, you can handle the complex parts of enterprise SSO—protocols, IdP integrations, and tenant management—while still keeping control of your own session logic.

This approach gives you what enterprises expect: secure, standards-based SSO with providers like Microsoft Entra, plus the flexibility to issue and manage your own tokens. It’s a foundation that scales with your customers, strengthens security, and delivers a smoother login experience for everyone.

To explore Descope on your own, sign up for a Free Forever account. Have questions? Book a demo with our team.