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 with OAuth

Learn more about how Stytch works and get up and running quickly using an example app. Want to dive into the products but not the code? Try out our demo app.

Frontend example apps

Leverage Stytch's flexibility to control authentication from your backend.

Backend example apps

Leverage Stytch's flexibility to control authentication from your backend.

Mobile example apps

Leverage Stytch's flexibility to control authentication from your backend.

iOS

Built with UIKit



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: Configure your project in the Stytch dashboard

    Before adding OAuth to your application you will need to make the following project configurations within the Stytch dashboard:

    1. Create a Login and Sign-up redirect URL on the redirect URL configuration page.
    2. Within SDK Configuration, authorize the domain(s) (eg. http://localhost:3000) the SDK will run on. Under Auth methods enable the OAuth toggle.
    3. Finally, under API keys, save your project's public_token for later.
  2. Step 2: 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.

  3. Step 4: 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
  4. Step 5: 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.

  5. Step 6: 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 { StytchLogin } from "@stytch/react";
    
    const Login = () => {
      const stytchProps = {
        config: {
          products: ['oauth'],
          oauthOptions: {
            providers: [{
              type: 'google',
              one_tap: true,
              position: 'embedded'
            }]
          },
        },
      };
    
      return (
        <div className="sign-in-container">
          <StytchLogin
            config={stytchProps.config}
          />
        </div>
      );
    };
    
    export default Login;
  6. Step 7: 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="
    	}'

Resources

Identity provider overview

Identity providers (IdPs), like Google, Apple, and GitHub, maintain user identity information and offer authentication services to developers and applications, so called relying parties.

oauth-diagram
This let's your users use a Single Sign-On (SSO) to login to your app without going through the extra step of creating an identity directly with your app.

In addition to offering identity management, IdPs often expose extensive functionality in their platform via API, e.g. reading and creating Google Calendar events or creating repos within GitHub. When you use Stytch OAuth, we automatically initiate a session with the IdP and return the necessary tokens to build on top of the provider's API.

Identity provider details table

Even though OAuth is a standard, IdPs can sometimes vary in data models and nomenclature within their own implementations. Stytch normalizes values and behavior as much as possible to ensure that you have a smooth integration with whichever providers you use.

The table below lists each OAuth provider we support and lets you know which values you should expect to see returned for each provider and the default session length. "—" indicates that the value is not applicable to the provider in question.

The access_token will be used to authenticate calls for a given user with the provider.

The refresh_token, if returned, will allow you to refresh a given session and keep it active. If the session lapses, you'll need to prompt the user to log in again via Stytch with the provider.

A JSON Web Token (jwt) offers a collection of information about a given session. Read more about JWTs returned by each provider in their section below.

Google offers two pathways for a user to authenticate, a traditional OAuth flow with a consent pane, or via Google One Tap. If a user enters through the Google One Tap flow, you will only receive a jwt and no access_token or refresh_token; you will not be able to leverage Google's API.

DEFAULT SCOPES

  • open_id
  • email
  • profile

RESOURCES

Stytch API referenceGmail API documentation

Log in with Amazon lets users log in with their Amazon customer accounts and offers data like name, email address, and zip code to build a more personalized experience.

DEFAULT SCOPES

  • profile

RESOURCES

Stytch API referenceAmazon scopesLog in with Amazon overview

Allow your users to log in with their Apple accounts. Apple does not offer any additional scopes. Note that Apple allows users to obfuscate their email address, and you may receive an email address like h79gps7k78@privaterelay.appleid.com. See the Resources section below to learn more.

DEFAULT SCOPES

  • name
  • email

RESOURCES

Stytch API referenceSign in with Apple overviewHow Hide my Email works

Log in with Bitbucket let's you build exciting tools on top of Atlassian's Bitbucket source control product.

DEFAULT SCOPES

  • account
  • email

RESOURCES

Stytch API referenceBitbucket scopesBitbucket API documentation

Log in with Coinbase let's users easily and securely sign in to your app and lets you integrate Coinbase supported cryptocurrencies into your applications.

DEFAULT SCOPES

  • account
  • email

RESOURCES

Stytch API referenceCoinbase scopesCoinbase API documentation

Discord OAuth login allows users to log into your app with their Discord account.

DEFAULT SCOPES

  • identify
  • email

RESOURCES

Stytch API referenceDiscord scopesDiscord API documentation

Facebook Login is a fast and convenient way for your users to create accounts and log into your app.

DEFAULT SCOPES

  • public_profile
  • email

RESOURCES

Stytch API referenceFacebook scopesFacebook API documentation

GitHub OAuth allows you to reach developers where they are and build amazing functionality on top of GitHub's API.

DEFAULT SCOPES

  • user:email

RESOURCES

Stytch API referenceGitHub scopesGitHub API documentation

GitLab OAuth unlocks amazing functionality within GitLab's fully featured API.

DEFAULT SCOPES

  • open_id
  • email
  • profile

RESOURCES

Stytch API referenceGitLab scopesGitLab API documentation

Log in via LinkedIn enables your application to reach the world's largest professional network.

DEFAULT SCOPES

  • r_liteprofile
  • r_emailaddress

RESOURCES

Stytch API referenceLinkedIn scopesLinkedIn API documentation

Log in with Microsoft helps your users sign in easily with their corporate or person Microsoft accounts and let's you leverage Microsoft's Graph API.

DEFAULT SCOPES

  • open_id
  • email
  • profile

RESOURCES

Stytch API referenceMicrosoft scopesMicrosoft API documentation

Log in with Slack let's your users log in with their Slack accounts.

DEFAULT SCOPES

  • openid
  • email
  • profile

RESOURCES

Stytch API referenceSlack scopesSlack API documentation

Log in with Twitch let's your users log in with their Twitch accounts.

DEFAULT SCOPES

  • account
  • email

RESOURCES

Stytch API referenceTwitch scopesTwitch API documentation

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.

If you get stuck while working through this guide, feel free to ask questions in our forum, via support@stytch.com, or in our Slack community.

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