OAuth overview

Stytch OAuth logins leverage industry standards like OAuth 2.0 and OpenID so you can easily integrate single sign-on options from popular social platforms and other third-party providers. While OAuth has many benefits, developers need to understand the OAuth framework well to implement it securely. Stytch's OAuth product simplifies the process by abstracting the implementation details of OAuth for developers.

Example apps using OAuth

Explore our OAuth components used in our SDK on Storybook.

Starting with a template

Examples using the Stytch frontend SDKs for all of our OAuth providers, including Google One Tap, for web and mobile.

example app

Guides

Step-by-step guides to quickly get up and running with Stytch OAuth.


Integrate Google OAuth via the API

Integrate Google OAuth into your existing login flow. The first three steps involve setting up a Google Cloud Project to get OAuth Credentials. Skip those steps if you already have your Google OAuth credentials.

  1. Step 1: Setup Google Project

    Before you can use the Stytch Google OAuth flow, you need to enter a Google OAuth client ID and client secret into the Stytch dashboard. Google requires you to create a Google Cloud project to get a client ID and client secret. Please follow the steps here to create one.

  2. Step 3: Setup Google OAuth Credentials

    After setting up the Google project and OAuth consent, go to this page to create the OAuth credentials. There is a create credentials button at the top of the page with an option to create an OAuth client id when selected. When the create OAuth credentials page loads, select Web application (regardless if it is a mobile or non-web application) for the application type and enter a name for your credentials. Under the Authorized redirect URIs section, add the following URL. After you finish creating the OAuth client, Google displays Client ID and client secret in a popup. You will need to enter them into the Stytch Dashboard here.

    https://test.stytch.com/v1/oauth/callback/REPLACE_WITH_OAUTH_CALLBACK_ID
  3. Step 4: Add redirect URLs to the Stytch dashboard

    Add the login and signup URLs to the project's list of predefined redirect URLs in the dashboard. For more information on why this step is necessary, please check out the documentation here.

  4. Step 5: Add the Google OAuth start URL

    Now that Stytch and Google are configured, you need to add Stytch Google OAuth to your application. The Stytch OAuth flow is started by having a user click the Google OAuth Start URL. This URL redirects the user to the Google OAuth sign-in page with all the required OAuth fields prefilled. Your frontend needs to display Stytch Google OAuth Start URL as a button and send the user to that URL when clicked.

    https://test.stytch.com/v1/public/oauth/google/start?public_token=PUBLIC_TOKEN
  5. Step 6: Authenticate OAuth request

    After Google redirects the user back to Stytch's API, the Stytch API redirects the user to your backend server with a token to either the login redirect URL or the signup redirect URL to verify Stytch redirected the user. If the response is a 200, the user is verified and can be logged in.

    curl --request POST \
    	--url https://test.stytch.com/v1/oauth/authenticate \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    	  "token": "SeiGwdj5lKkrEVgcEY3QNJXt6srxS3IK2Nwkar6mXD4="
    	}'

Integrate Google One Tap via the SDK

Implement Google One Tap via the Javascript SDK.

  1. Step 1: Setup Google Project

    Before you can use the Stytch Google OAuth flow, you need to enter a Google OAuth client ID and client secret into the Stytch dashboard. Google requires you to create a Google Cloud project to get a client ID and client secret. Please follow the steps here to create one.

  2. Step 3: Setup Google OAuth Credentials

    After setting up the Google project and OAuth consent, go to this page to create the OAuth credentials. There is a create credentials button at the top of the page with an option to create an OAuth client id when selected. When the create OAuth credentials page loads, select Web application (regardless if it is a mobile or non-web application) for the application type and enter a name for your credentials. Under the Authorized JavaScript origins section, add the origin where One Tap will appear. For example, if you plan on showing One Tap at https://example.com/login, enter https://example.com. If you're using localhost for testing, we recommend adding both http://localhost and http://locahost:[port]. Under the Authorized redirect URIs section, add the URL below. After you finish creating the OAuth client, Google displays Client ID and client secret in a popup. You will need to enter them into the Stytch Dashboard here.

    https://test.stytch.com/v1/oauth/callback/REPLACE_WITH_OAUTH_CALLBACK_ID
  3. Step 4: Add redirect URLs to the Stytch dashboard

    Add the login and signup URLs to the project's list of predefined redirect URLs in the dashboard. For more information on why this step is necessary, please check out the documentation here.

  4. Step 5: Add the SDK to your app

    Now that Stytch and Google are configured, you need to add the Stytch SDK to your application.

    import React from "react";
    import { Stytch } from "@stytch/stytch-react";
    
    const Login = () => {
      const STYTCH_PUBLIC_TOKEN = "PUBLIC_TOKEN";
      const stytchProps = {
        loginOrSignupView: {
          products: ['oauth'],
          oauthOptions: {
            providers: [{
              type: 'google',
              one_tap: true,
              position: 'embedded'
            }]
          },
        },
        publicToken: STYTCH_PUBLIC_TOKEN,
      };
    
      return (
        <div className="sign-in-container">
          <Stytch
            publicToken={stytchProps.publicToken}
            loginOrSignupView={stytchProps.loginOrSignupView}
          />
        </div>
      );
    };
    
    export default Login;
  5. Step 6: Authenticate OAuth request

    After Google redirects the user back to Stytch's API, the Stytch API redirects the user to your backend server with a token to either the login redirect URL or the signup redirect URL to verify Stytch redirected the user. If the response is a 200, the user is verified and can be logged in.

    curl --request POST \
    	--url https://test.stytch.com/v1/oauth/authenticate \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    	  "token": "SeiGwdj5lKkrEVgcEY3QNJXt6srxS3IK2Nwkar6mXD4="
    	}'

Adding PKCE to an OAuth flow

Proof Key for Code Exchange (PKCE) is a specification that builds on OAuth 2.0 to create a more secure login flow.

In the original OAuth authorization code flow, an IdP issues a one-time use code to the app, which is exchanged along with a client_idand client_secret for an auth token. For certain types of apps (i.e. SPAs, mobile apps, or native apps) there was no mechanism to hide the client_secret, which must be included in the app's source code and reused on every request. This meant that an attacker would be able to impersonate a user if the attacker gained access to the one-time use code. Codes in a URL can be leaked in many different ways - either through improper logging, HTTP Referrer headers, or even through another exploit like XSS.

PKCE introduces a one-time secret for each authorization flow. This secret, called a code_verifier, is generated and stored by the app on the user's device. Before the user is redirected to the IdP, the verifier is hashed to produce a code_challenge. This challenge is passed as a query parameter during the authentication flow, e.g. /oauth/authenticate?code_challenge=E9Mel....

After the IdP has validated the user's credentials, the user is redirected back to the app with a securecode. Now, the app must submit the code along with the originalcode_verifier. The IdP hashes the submitted code_verifier and validates that it matches thecode_challenge passed as a query parameter earlier. This check ensures that the token has not been leaked, and that it is being handled by the same user that was seen at the start of the flow.

This guide will show you how to add PKCE support to your Stytch OAuth integration for added security. A PKCE integration is required for applications that use native callback URLs, for example appname://some/callback on mobile. Stytch's support for PKCE differs slightly from the original specification - for example we do not permit plain verifiers to be used - but the original idea of strengthening app security with a unique secret on every request remains the same.

As you’re working through this guide, feel free to ask any questions if you get stuck in our Slack community or reach out to us at support@stytch.com.

Choose integration method

JavaScript SDK
  1. Step 1: Enable PKCE for your app

    Enable PKCE for all OAuth logins performed by the JavaScript SDK. By flipping this setting, you tell the Javascript SDK to use PKCE for all UI components, and to reject any OAuth logins that do not use PKCE. In order to do so, toggle the option in the SDK Configuration page of the Stytch dashboard. This makes your application resistant to attacks like Login CSRF in which an attacker can trick a victim into logging in to the wrong account.

    Note: The legacy oauth.$provider.getURL() method is not compatible with PKCE. If you are using this method already in your codebase, complete Step 2 before enabling PKCE.

  2. Step 2: Start the OAuth flow

    Call one of the oauth.$provider.start() methods to start the OAuth flow. The SDK will generate a code_verifier and store it in local storage before redirecting the user to Stytch's OAuth start endpoint. If you use the SDK's built in OAuth UI this step is already handled for you.

    function OAuthStartButton() {
      const stytch = useStytch();
      const startOAuthFlow = useCallback(() => stytch.oauth.google.start({
        login_redirect_url: 'https://example.com/callback',
        signup_redirect_url: 'https://example.com/callback',
        custom_scopes: ['https://www.googleapis.com/auth/calendar']
      }), [stytch])
    
      return (
        <button onClick={startOAuthFlow}>
          Click here to log in with Google
        </button>
      );   
    }
    
  3. Step 3: Authenticate the OAuth token

    At the route that the user is redirected to after the OAuth flow, pull the token out of the URL params and call oauth.authenticate(token) to exchange the token for a Stytch session. The SDK will automatically retrieve the code_verifier created earlier from local storage and pass it on to the Stytch servers.

    function OAuthCallback() {
      const stytch = useStytch();
      useEffect(() => {
        const params = new URLSearchParams(window.location.search);
        const token = params.get('token');
        if(!token) {
          // TODO: Handle redirect back to logged-out view 
        }
        stytch.oauth.authenticate(token, {
          session_duration_minutes: 60,
        }).then(() => {
          // TODO: Redirect to final logged-in view
        })
      }, [stytch]);
    
      return (
        <div>
          Authenticating....
        </div>
      );   
    }