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
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',
    });

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

Authenticate

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

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
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',
    });

  return <button onClick={startOAuth}>Log in with Google</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 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 = () => {
  const config = {
    products: ['oauth'],
    sessionOptions: { sessionDurationMinutes: 60 },
    authFlowType: 'Discovery',
    oauthOptions: {
      loginRedirectURL: window.location.origin + '/authenticate',
      signupRedirectURL: window.location.origin + '/authenticate',
      providers: ['google', 'microsoft'],
    },
  };

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

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

  return <StytchB2B callbacks={callbacks} config={config} styles={style} />;
};

export default OAuth;