Back to blog

Single Sign-On example

Auth & identity

Apr 25, 2025

Author: Stytch Team

Single Sign-On example

Single sign-on (SSO) gives employees seamless access to multiple company applications with a single login. Given the ever-increasing number of applications we use on a daily basis, it has become a highly requested feature for many of those seeking enterprise software solutions.

Besides improved user experience for their employees, organizations have many other compelling reasons for seeking out SaaS applications that support SSO. SSO also helps address poor password practice, offers improved security, centralizes access management for IT, and reduces overall support overhead.

In this article, we’ll walk through the process of implementing SSO in your application. We’ll include handy visual diagrams of the key concepts, an introduction to the protocols, single sign-on example code snippets, and discussion about the common challenges you may face along the way.

What is Single Sign-On (SSO)?

Single sign-on enables a user to access multiple applications, logging in only once, without the need to re-authenticate every time. Before we look at a real-world analogy, let’s start by understanding some basic concepts:

  • User: the person accessing the application(s)
  • Identity Provider (IdP): a service that authenticates users and verifies their identity to other applications
  • Service Providers (SP): the applications or services that the user needs to access
  • Authentication tokens: secure digital credentials that allow users to navigate between applications without re-authenticating
  • Security protocol: a standardized method that defines how authentication information is exchanged between the identity provider and the service provider (examples include SAML and OAuth 2.0/OIDC)

Think of SSO like a VIP wristband at a music festival. Once you (the User) have been verified at entry by security (the Identity Provider), you can access other areas of the festival (the Service Providers) using your wristband (the authentication token).

There’s another good parallel to this analogy: Since you don't have to repeatedly retrieve and share your ID all the time, you could leave it safely locked away in your car, reducing the chances of you losing it or having your ID fall into the wrong hands. In the same way, using SSO instead of multiple passwords decreases the risk of your credentials getting phished or otherwise stolen.

As shown in our diagram, single sign-on makes authentication much less strenuous by letting users access multiple applications with only one login.

Diagram illustrating a single sign-on example, comparing the process before and after SSO implementation

Key protocols for implementing SSO

Implementing SSO in your application also relies on knowledge of at least one of the following security protocols:

  • SAML (Security Assertion Markup Language): a mature XML-based protocol primarily used when implementing enterprise SSO
  • OpenID Connect (OIDC): a more modern SSO protocol used in web and mobile applications. OIDC is built on top of OAuth 2.0, giving it authentication capabilities.
  • OAuth 2.0: an authorization framework that provides third-party applications limited access to a user’s resources without requiring the user to share their credentials. It doesn't do authentication, so it's usually used in conjunction with OIDC.

There are several factors to consider when choosing either SAML or OIDC, such as whether you are working for a large corporate enterprise that uses traditional identity providers (SAML), or whether you need something more modern and better suited for web and mobile applications (OIDC).

Fortunately, many identity providers now support both SAML-based and OIDC-based SSO protocols, offering you the flexibility to select the protocol that best aligns with your requirements or the one you’re most comfortable using.

To find out more, read our article on the differences between SAML and OIDC.

What’s the difference between Enterprise (B2B) SSO and social login?

When discussing SSO, it’s important to know the difference between enterprise SSO and social login. They are sometimes confused, can present themselves similarly to the user, and can overlap significantly.

Enterprise (B2B) SSO

Enterprise SSO is designed for employees within organizations, allowing them to access company tools and software with a single login.

The key distinguishing feature here is that the organization itself owns and manages their identity provider instance (powered by platforms such as Microsoft Entra ID, Okta or Ping Identity). With Enterprise SSO, the organization has completely control over defining and verifying the identity of each user/emplotee, including provisioning, deprovisioning and enforcing security policies. This is typically what a B2B customer is looking for when asking if your application supports SSO.

This diagram illustrates how employees can gain access to multiple company applications through a centralized identity provider managed by IT.

Diagram showcasing an enterprise single sign-on example.

From the employee's point of view, SSO makes using company applications a much smoother, more integrated experience. They simply log into a core application like Salesforce once. Then, when they need to access other tools such as Workday or Slack later in the day, they're already logged in. The employee doesn't have to enter their credentials again, since their identity and access is managed centrally behind the scenes.

Social login

Social login (sometimes referred to as “social SSO” or “consumer SSO”) allows users to log into applications using existing accounts from providers such as Google, Microsoft, or Facebook. You often see these as “Sign in with Google,” or “Continue with Microsoft” buttons on an application login screen.

Unlike Enterprise SSO, social login delegates the identity verification process to external identity providers that it doesn't control. The application must trust these third-party providers to properly verify and authenticate users, without having direct oversight of the identity management process.

As visualized below, this approach lets users leverage their existing accounts to access various consumer applications without creating new credentials.

Diagram showing an example social login flow.

The diagram illustrates this social login flow in action: Spotify, Pinterest, and Airbnb all allow you to sign in using your existing Facebook, Google, or Apple account, respectively, without needing to create a new account specific to their platform.

Under the hood, social login typically uses the OIDC and OAuth 2.0 protocols for authentication and authorization. This differs from enterprise single sign-on scenarios that more commonly leverage SAML.

The fundamental difference between Enterprise SSO and social login in the trust relationship and control over identities: enterprise SSO gives organizations direct ownership and management of their users' identities, while social login requires applications to trust external providers to verify users.

Can I implement both social login and enterprise SSO?

Absolutely! Many SaaS applications serve both business users and personal users — for example, offering both “Continue with Google” and “Single sign-on (SSO)” options.

Applications like Slack and Notion, each offering both individual and enterprise plans, support this dual login approach. With Slack, you can log into workspaces using either a personal account like a Gmail address or an enterprise account from Google Workspace or Microsoft 365 that is linked to the organization's SSO. Notion similarly allows logging in with various work and personal Microsoft or Google accounts, routing enterprise accounts through SSO where configured.

SSO example authentication flow

Let's examine a practical single sign-on example auth flow to understand how it works.

A good way to understand how the authentication flow for SSO works is by looking at the real-world example discussed previously: after an employee logs into Salesforce, they are automatically logged into Microsoft 365, Slack, and Workday when they navigate to these applications at a later time.

The following example demonstrates a SAML-based SSO authentication flow using SP-initiated pattern, which is the most common SSO implementation. In this approach, the authentication process begins when a user attempts to access your application (the Service Provider) directly.

Note that there are also IdP-initiated flows where users start at their company portal and access your applications from there, but those require different handling and aren't covered in this example.

The diagram below shows the technical interactions between the user, service providers, and identity provider during an SP-initiated SSO auth process.

Diagram showing an SSO authentication flow.

The first-time authentication process follows these key steps:

  1. Access request: The user tries to access the application (for example, Salesforce).
  2. Redirect to IdP: The application redirects the user to the identity provider.
    1. The application generates a signed auth request.
    2. Application redirects users to the identity provider with the request.
    3. Browser follows the redirect to the identity provider login page.
  3. User authentication: The user logs in at the identity provider.
    1. The identity provider provides a login prompt to the user.
    2. The user identifies themselves (username/password, MFA).
  4. Token generation and redirection to the application.
    1. The identity provider generates a token (SAML assertion, JWT, or OIDC).
    2. The identity provider redirects the user to the application’s callback URL with the token.
  5. Token validation and session creation.
    1. The application validates the token.
    2. The application creates a user session.

Once the user has an active session with the identity provider, the next time they try to access a new application, that application checks with the identity provider to see if a valid session already exists. If so, the user is logged in automatically! This is the beauty of SSO.

Single sign-on code example

Let’s work through the SSO auth flow step by step and see what this would look like in code.

Steps 1 and 2: Access request and redirecting to the IdP

Dealing with SAML assertions can get complicated, as they're written in XML and need parsing. It's much simpler to use an authentication library to handle this for you. This code example is in Node.js, so we're using the Passport Node.js authentication library.

When a user first tries to access your application, if no session exists for them, you can redirect them to a /login endpoint, which in turn will need to redirect them to the identity provider for authentication.

// Configure SAML strategy with your IdP details
const passport = require('passport');
const { Strategy } = require('passport-saml');

passport.use(new Strategy({
  entryPoint: 'https://idp.example.com/saml2/sso',
  issuer: 'your-app-entity-id',
  callbackURL: '/auth/saml/callback',
  cert: fs.readFileSync('./idp-certificate.pem', 'utf8')
}, verifyCallback));

// 'Login' route triggers redirect to IdP
app.get('/login', 
  passport.authenticate('saml', { 
    failureRedirect: '/login-error',
    failureFlash: true 
  })
);

Some configuration of Passport is required, and you do this using a strategy. A strategy in Passport tells it what authentication methods to use, including the authentication protocol (in this case, SAML), and further configuration details like your identity provider's URL.

Let’s break down the main components of the strategy:

  1. entryPoint: the URL of the identity provider where users are redirected to login
  2. issuer: a unique identifier for your application that helps the IdP know which application is requesting authentication
  3. callbackURL: an endpoint in your application where the identity provider will send the SAML response after successfully authenticating the user
  4. cert: the public certificate of the IdP, which is typically downloaded from the IdP directly and then stored locally in your application

In production, you would usually store parameters such as the entry point, issuer, and callback URL in an environment variables file.

Step 3: User authentication

This step happens at the identity provider, and not in your application. The IdP will present a login page where the user can enter their credentials and possibly complete multifactor authentication, such as biometric login or a one-time passcode.

Step 4 and 5: Token generation, validation, and session creation

Once the IdP has successfully authenticated the user, it will generate a SAML assertion and redirect back to the application’s callback URL, which then needs to parse the SAML response, validate it, and extract user information. Luckily, Passport's authenticate function handles all these things for you! The user information is then used to create a session for the authenticated user, and then finally the user can be redirected to the page they were initially trying to access.

// Handle the callback from the identity provider
app.post('/auth/saml/callback',
    // authenticates the user (or redirects them on failure)
    passport.authenticate('saml', { 
    failureRedirect: '/login-error',
    failureFlash: true 
  }),

  // Create user session after successful authentication
  (req, res) => {
    // User is now authenticated and added to session
    const nameID = req.user.nameID;
    const email = req.user.email;
    const groups = req.user.groups || [];
    
    // Map IdP groups to application roles
    const roles = mapGroupsToRoles(groups);
    
    // Store user info in session
    req.session.user = {
      id: nameID,
      email,
      roles,
      authenticated: true
    };
    
    // Redirect to the application's main page
    res.redirect('/dashboard');
  }
);

Further SSO implementation requirements

Beyond the basic single sign-on example we've shown, a secure production SSO implementation requires some additional thought.

Security

Supporting SSO means relying on the identity provider as a central point of access control. If the IdP experiences issues, it can have a widespread impact on your business. In addition, SSO implementations are vulnerable to a variety of other attack vectors including identity mix-up attacks, cross-tenant leaks, and metadata spoofing. Protecting this critical pathway

  • SAML vulnerabilities: Implementing SAML incorrectly can leave your application exposed to a whole host of vulnerabilities and “gotchas”: XML signature wrapping attacks, accidental disclosure of server data, session hijacking (response replay) and open improperly validated certificates, to name just a few!
  • Token validation: Continuously verify digital signatures, check expiration times, and verify that authentication tokens were created specifically for your application.
  • Session management and lifecycle: Handling authentication tokens correctly requires proper validation of signatures and expiration dates, secure storage mechanisms, and renewal processes that don’t disrupt the user. Beyond this, you’ll need to consider coordinated logout and carefully handle network interruptions during authentication with the identity provider.
  • Protecting authenticated routes: You'll need to add middleware that checks if a user is authenticated before giving them access to your protected URLs.

Authorization

Authentication verifies identity, but authorization determines what authenticated users can access. These features ensure proper access control within your application.

  • “Break-glass” admin accounts: In the case of an IdP failure, the business will need administrative accounts that can access the system without using SSO.
  • Permission mapping: Your application needs to be able to map user attributes (like groups) from the IdP to your internal permission system. For example, if a user authenticates via Azure AD and is in the “Finance” group, then your application needs to be able to recognize this and grant the equivalent permissions. This isn’t automatic; administrators will need to be able to configure it using your application’s interface and define which external groups correspond to which permissions in your application. In a multi-tenant setup, each B2B customer might have different groups, so your application needs to allow this to be configured on a per-customer basis.

Enterprise features

Enterprise customers expect sophisticated capabilities that simplify user management and enhance the authentication experience across their organization.

  • Multi-tenant support: Your auth system must be able to isolate data and configuration for each of your individual B2B customers, all from a single codebase. This often includes supporting multiple identity providers so each tenant can authenticate their users using their own IdP.
  • Multiple SSO connections for a single tenant: Support several authentication methods within a single B2B customer. For example, the business might require that employees login via the corporate directory, but contractors might use a different IdP. You may need to set up logic to route users based on factors such as email domain, network location, or allowing users to explicitly select their identity provider from a dropdown list.
  • Passive login: When a user returns to your application at a later time, your code should check for existing sessions first and log the user in automatically using their existing token.
  • Just-in-Time user account creation: Automate creating user accounts after first login. This includes parsing user attributes from the returned IdP authentication token and mapping them to your user schema.

Other considerations

Beyond core implementation features, these operational factors ensure your SSO solution remains reliable, compliant, and performant over time.

  • Testing and validation: As protocols evolve and new vulnerabilities emerge, you’ll need to keep a close eye on your SSO implementation. Adding support for additional IdPs will multiply the testing requirements, and updates to any provider might break existing integrations. Comprehensive testing and test automation is key.
  • Compliance and regulatory requirements: Certain data-sensitive industries, such as healthcare and finance, face very strict regulatory requirements. Some of these requirements might include specific session timeouts, auditing and logging of authentication events, regular security assessments, or constraints about where identity information can be stored.
  • Scaling and performance: High-traffic applications can easily suffer from performance issues if their SSO implementation isn't architected with efficiency in mind. Avoiding a bottleneck in your application will involve minimizing latency during authentication redirects, ensuring resilience against high traffic spikes (such as morning login rushes), and efficiently handling token validation, which can become a bottleneck in itself, especially when it involves CPU-intensive cryptographic operations like signature verification.

Implementing SSO in a way that gracefully handles all of these challenges requires significant expertise and ongoing effort.

Stytch: a comprehensive single sign-on solution

With this single sign-on example as a foundation, you can start implementing secure authentication for your enterprise applications, but it’s clear that supporting SSO from scratch requires significant development resources and ongoing maintenance.

With Stytch, the entire SSO implementation can be dramatically simplified using our pre-built UI. Here’s an example:

import { StytchB2B } from "@stytch/nextjs/b2b";
import { B2BProducts, AuthFlowType } from "@stytch/vanilla-js";

const Login = () => {
  // For SSO Discovery login
  const config = {
    authFlowType: AuthFlowType.Discovery,
    products: [B2BProducts.sso, B2BProducts.oauth],
    oauthOptions: { providers: [{type: 'google'}, {type: 'microsoft'}]}
  };

  return <StytchB2B config={config} />;
...

The StytchB2B component renders the appropriate login interface for you, in addition to executing calls to the Stytch API to handle redirects, process SAML assertions, manage user sessions securely and provide appropriate error handling and feedback. This eliminates hundreds of lines of custom code and significantly reduces the risk of security vulnerabilities in your authentication process.

Stytch SSO and OAuth

For back-end only implementation and accessing the API layer directly, Stytch’s authentication approach is equally streamlined:

@app.route("/authenticate", methods=["GET"])
def authenticate() -> str:
    token_type = request.args["stytch_token_type"]
    if token_type == "sso":
        resp = stytch_client.sso.authenticate(sso_token=request.arg["token"])
        if resp.status_code != 200:
            return "something went wrong authenticating token"
        
        # member is successfully logged in
        member = resp.member
        session["stytch_session"] = resp.session_jwt
        return member.json()

Beyond the implementation code itself, Stytch addresses the other critical challenge: administration. Enterprise customers need a way to configure their SSO connections, and building this management interface is often as time-consuming as implementing the auth flow itself.

Stych’s Admin Portal solves this problem by providing embeddable UI component that allow your customers to self-manage their SSO connections directly within your application. This eliminates the need to build custom interfaces for SSO configuration and reduces customer support burden by enabling IT teams to:

  • Configure SSO connections without developer assistance
  • Manage identity provider settings and certificates
  • Set up automatic role assignments based on identity provider groups
  • Create and enforce organization-wide authentication policies
Admin Portal

With Stytch, you can quickly deploy secure, scalable SSO and focus on your core application features instead. Stytch offers:

  • SSO implementations with pre-built UI components and backend SDKs
  • Handling of SAML and OIDC protocols
  • Support for a wide range of identity providers including Okta, Microsoft Entrada ID, Google Workspace, and many more
  • Role-base access control (RBAC) via groups and SCIM alongside SSO
  • User provisioning via SCIM alongside SSO
  • A fully self-serve SSO management dashboard with Admin Portal

Organizations that implement enterprise-grade SSO using solutions like Stytch can see substantial improvement in user experience, fewer support tickets, and streamlined experience for their B2B clients. By leveraging both Stytch, you can deliver a complete SSO solution with minimal engineering effort while providing your customers with the control they need.

Try Stytch today and simplify your single sign-on implementation with our powerful, developer-friendly authentication platform.

Build with Stytch

APIs and SDKs for authentication, authorization, security and fraud prevention

Learn more



Share this article