OAuth

OAuth is a popular authentication framework that delegates authentication to an external identity provider (often shortened to IdP) like Google, Facebook, Apple, and Microsoft. A user relies on their membership from that provider to sign in instead of creating another password, and developers can enrich their users' experiences with the information shared by the providers.

The JavaScript SDK provides a pre-built UI for OAuth flows, as well as methods to start and authenticate OAuth flows that you can connect to your own UI. Use either of these approaches to quickly get up and running with OAuth.

Methods

Start OAuth flow

The oauth.$provider.start() methods start OAuth flows by redirecting the browser to one of Stytch's OAuth Start endpoints. One of organization_id or slug is required to specify which organization the user is trying to access. If the organization that the user is trying to access is not yet known, use the oauth.$provider.discovery.start() method instead.

The method will also generate a PKCE code_verifier and store it in local storage on the device (See the PKCE OAuth guide for details). If your application is configured to use a custom subdomain with Stytch, it will be used automatically.

  • oauth.google.start()
  • oauth.microsoft.start()

Method parameters


organization_idstring

slugstring

login_redirect_urlstring

signup_redirect_urlstring

custom_scopesstring

provider_paramsobject
import { useStytchB2BClient } from '@stytch/react';

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

  const startOAuth = () =>
    stytchClient.oauth.google.start({
      organization_id: 'organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931',
      login_redirect_url: 'https://example.com/authenticate',
      signup_redirect_url: 'https://example.com/authenticate',
      provider_params: {
        login_hint: 'example_hint@stytch.com'
      }
    });

  return <button onClick={startOAuth}>Log in with Google</button>;
};

Display Google One Tap

The oauth.googleOneTap.start() method will show the Google one tap prompt in the top right corner of the user's browser. An organization_id is required to specify which organization the user is trying to access. If the organization that the user is trying to access is not yet known, use the oauth.googleOneTap.discovery.start() method instead.

If the end user clicks to sign in with Google One Tap, Stytch will verify the response and redirect to the login_redirect_url or signup_redirect_url provided, or the default redirect URLs if none are specified. A PKCE code_verifier will also be generated and store it in local storage on the device (See the PKCE OAuth guide for details). If your application is configured to use a custom subdomain with Stytch, it will be used automatically.

Once the user is successfully redirected, you can collect the Stytch OAuth token from the URL query parameters, and call the OAuth Authenticate endpoint to complete the authentication flow.

Google One Tap does not return access tokens. If you wish to retrieve the user's access token, you'll need to use a regular Google OAuth flow.


Method parameters


organization_id*string

login_redirect_urlstring

signup_redirect_urlstring
import { useStytchB2BClient } from '@stytch/react';

export const GoogleOneTap = () => {
  const stytchClient = useStytchB2BClient();

  const showGoogleOneTap = () =>
    stytchClient.oauth.googleOneTap.start({
      organization_id: 'organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931',
      login_redirect_url: 'https://example.com/authenticate',
      signup_redirect_url: 'https://example.com/authenticate',
    });

  return <button onClick={showGoogleOneTap}>Show Google One Tap</button>;
};

Authenticate

The authenticate method wraps the Authenticate OAuth API endpoint which validates the OAuth token passed in.

If there is a current Member Session, the SDK will call the endpoint with the session token. This will add the new factor to the existing Member Session.

If there is an intermediate session token, the SDK will call the endpoint with it. If the resulting set of factors satisfies the organization's primary authentication requirements and MFA requirements, the intermediate session token will be consumed and converted to a Member Session. If not, the same intermediate session token will be returned.

If this method succeeds and the Member is not required to complete MFA, the Member will be logged in, granted an active session, and the session cookies will be minted and stored in the browser.

If this method succeeds and MFA is required, the intermediate session token will be stored in the browser as a cookie.

You can listen for successful login events anywhere in the codebase with the stytch.session.onChange() method or useStytchMemberSession hook if you are using React.


Method parameters


oauth_token*string

session_duration_minutes*int

localestring
import React, { useEffect } from 'react';
import { useStytchB2BClient, useStytchMemberSession } from '@stytch/react';

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.oauth.authenticate({
        oauth_token: token,
        session_duration_minutes: 60,
      });
    }
  }, [stytchClient, session]);

  return <div>Loading</div>;
};

RESPONSE

{
    "status_code": 200,
    "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
    "member_id": "member-test-32fc5024-9c09-4da3-bd2e-c9ce4da9375f",
    "organization_id": "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931",
    "session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q",
    "session_jwt": "eyJ...",
    "intermediate_session_token": "",
    "member_authenticated": true,
    "mfa_required": null,
    "session": {...},
    "member": {...},
    "organization": {...},
  }

Start Discovery OAuth flow

The oauth.$provider.discovery.start() methods start OAuth flows by redirecting the browser to one of Stytch's OAuth Discovery Start endpoints. The method will also generate a PKCE code_verifier and store it in local storage on the device (See the PKCE OAuth guide for details). If your application is configured to use a custom subdomain with Stytch, it will be used automatically.

  • oauth.google.discovery.start()
  • oauth.microsoft.discovery.start()

Method parameters


discovery_redirect_urlstring

custom_scopesstring

provider_paramsobject
import { useStytchB2BClient } from '@stytch/react';

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

  const startOAuth = () =>
    stytchClient.oauth.google.discovery.start({
      login_redirect_url: 'https://example.com/authenticate',
      signup_redirect_url: 'https://example.com/authenticate',
      provider_params: {
        login_hint: 'example_hint@stytch.com'
      }
    });

  return <button onClick={startOAuth}>Log in with Google</button>;
};

Display Discovery Google One Tap

The oauth.googleOneTap.discovery.start() method will show the Google one tap prompt in the top right corner of the user's browser.

If the end user clicks to sign in with Google One Tap, Stytch will verify the response and redirect to the discovery_redirect_url provided, or the default redirect URL if none is specified. A PKCE code_verifier will also be generated and store it in local storage on the device (See the PKCE OAuth guide for details). If your application is configured to use a custom subdomain with Stytch, it will be used automatically.

Once the user is successfully redirected, you can collect the Stytch OAuth token from the URL query parameters, and call the OAuth Discovery Authenticate endpoint to complete the discovery authentication flow.

Google One Tap does not return access tokens. If you wish to retrieve the user's access token, you'll need to use a regular Google OAuth flow.


Method parameters


discovery_redirect_urlstring
import { useStytchB2BClient } from '@stytch/react';

export const GoogleOneTapDiscovery = () => {
  const stytchClient = useStytchB2BClient();

  const showGoogleOneTapDiscovery = () =>
    stytchClient.oauth.googleOneTap.discovery.start({
      discovery_redirect_url: 'https://example.com/authenticate',
    });

  return <button onClick={showGoogleOneTapDiscovery}>Show Google One Tap Discovery</button>;
};

Discovery Authenticate

The authenticate method wraps the Authenticate Discovery OAuth API endpoint which validates the OAuth token passed in. If this method succeeds, the intermediate session token will be stored in the browser as a cookie.


Method parameters


discovery_oauth_token*string
import React, { useEffect } from 'react';
import { useStytchB2BClient, useStytchMemberSession } from '@stytch/react';

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.oauth.discovery.authenticate({
        discovery_oauth_token: token,
      });
    }
  }, [stytchClient, session]);

  return <div>Loading</div>;
};

RESPONSE

200
{
    "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
    "status_code": 200,
    "intermediate_session_token": "SeiGwdj5lKkrEVgcEY3QNJXt6srxS3IK2Nwkar6mXD4=",
    "email_address": "sandbox@stytch.com",
    "discovered_organizations": [{...}, {...}]
  }

UI components

Our Javascript SDK wraps our start OAuth endpoint which kicks off the OAuth flow for your users. You'll want to set up each OAuth provider in your Dashboard before using it in the SDK. The SDK supports Google (including Google One Tap) and Microsoft OAuth.

To add OAuth to the login UI, add oauth to the products array in the configuration and the appropriate oauthOptions.

To see all authentication and customization options, see the UI config section below.

import { StytchB2B } from '@stytch/react/b2b';
import React from 'react';

const OAuth = () => {
  
  // Example config for the Discovery auth flow, to be hosted on a
  // generic login page
  const discoveryConfig = {
    authFlowType: "Discovery",
    products: ['oauth'],
    oauthOptions: {
      discoveryRedirectURL: window.location.origin + '/authenticate',
      providers: [{ type: 'google', one_tap: true }, { type: 'microsoft' }],
    },
    sessionOptions: {
      sessionDurationMinutes: 60,
    },
  };
  
  // Example config for the Organization auth flow, to be hosted on an
  // Organization-specific login page
  const organizationConfig = {
    authFlowType: "Organization",
    products: ['oauth'],
    oauthOptions: {
      loginRedirectURL: window.location.origin + '/authenticate',
      signupRedirectURL: window.location.origin + '/signup',
      providers: [{ type: 'google', one_tap: true }, { type: 'microsoft' }],
    },
    sessionOptions: {
      sessionDurationMinutes: 60,
    },
  };

  const style = {
    fontFamily: 'Arial',
  };

  const callbacks = {
    onEvent: ({ type, data }) => {
      console.log(type, data);
    },
    onError: (data) => {
      console.log(data);
    },
  };

  // Choose either the discoveryConfig or the organizationConfig
  return <StytchB2B callbacks={callbacks} config={discoveryConfig} styles={style} />;
};

export default OAuth;