Skip to main content

Authentication flow


Before you begin, make sure you’ve completed the SSO provider setup steps.

Overview

This guide walks through integrating SSO using Stytch’s headless frontend SDKs. This approach gives you complete control over your UI while handling authentication logic on the frontend.Both and Organization-specific authentication flows are supported.
The Discovery flow is designed for situations where end users are signing up or logging in from a central landing page, and have not specified which they are trying to access.

Prerequisites

  1. Complete the steps in the SSO provider setup guide
  2. Enable the Frontend SDKs in your Stytch Dashboard

Implementation

1

Discover available SSO Connections

If you have a centralized login page, prompt the user for their email and call sso.discoverConnections.
import { useStytchB2BClient } from '@stytch/react/b2b';

export const SSOConnectionsDiscovery = () => {
  const stytch = useStytchB2BClient();

  const discoverSSOConnections = (email) => {
    stytch.sso.discoverConnections(email);
  };

  return <button onClick={() => discoverSSOConnections(email)}>Continue</button>;
};
The sso.discoverConnections() method returns an array of SSO Connections. Use the display_name and idp_type to render the available options, then pass the selected connection_id into the next step.
2

Start the SSO flow

Use the selected connection_id to initiate the SSO flow.
import { useStytchB2BClient } from '@stytch/react/b2b';

export const Login = ({ connectionId }) => {
  const stytchClient = useStytchB2BClient();

  const startSSO = () =>
    stytchClient.sso.start({
      connection_id: connectionId,
    });

  return <button onClick={startSSO}>Log in with SSO</button>;
};
The user will be redirected to their IdP to authenticate.
3

Handle the SSO callback

After the SSO handshake, Stytch redirects to your Login or Signup Redirect URL with a token in the URL. Call sso.authenticate to finish the login process.
import { useEffect } from 'react';
import { useStytchB2BClient, useStytchMemberSession } from '@stytch/react/b2b';

export const Authenticate = () => {
  const stytchClient = useStytchB2BClient();
  const { session } = useStytchMemberSession();

  useEffect(() => {
    if (session) {
      window.location.href = 'https://example.com/profile';
    } else {
      const token = new URLSearchParams(window.location.search).get('token');
      stytchClient.sso.authenticate({
        sso_token: token,
      });
    }
  }, [stytchClient, session]);

  return <div>Loading</div>;
};
The Stytch frontend SDK will store stytch_session_token and stytch_session_jwt in cookies for you. See session cookie management.