How to authenticate Google Requests with Stytch OAuth API

I recently came across this service called Stytch which allows for passwordless authentication solutions after reading about them raising a series B round. As any tech nerd, I’m always interested in these new services popping up. Turns out, you can do OAuth logins!

What better way to get familiar with a service than by trying them out?

Previously, I made a post about authorization: How to authorize requests to Google Calendar API . This time, we’re going to focus on just the authentication piece with Stytch. To clarify:

Authorization is the ability to make requests to Google API to modify resources, authentication is verifying that a user is who they say they are.

You can find the original docs in their official guides. This post just adds a bit more information that I found a bit unclear while going through it on my own. I use Python with flask here similar to my previous post. You don’t really need to know a depth of either, a brief introduction would suffice for this post as it’s really about OAuth authenticate and Stytch than it is about anything else.

At a high level, what we have to do is:

  1. Create a GCP Project
  2. Create an OAuth consent screen*
  3. Create OAuth credentials*
  4. Create a login and sign up route for Stytch
  5. Embed a button to your web app (that redirects users to a special Stytch URL which starts the authentication process with Google)
  6. Authenticate a special token given to you by Stytch which verifies whether a user was successfully authenticated or not

As you can see, the initial steps are, overall, still the same with a slight twist. Though you have to create a new GCP project, add an OAuth consent screen, and create OAuth credentials you need to add Stytch specific configurations when creating the consent screen and credentials.

  1. When creating the OAuth consent screen you must add stytch.com as an authorized domain.
  2. When creating the OAuth credentials, you need to add a special URL given by Stytch as the redirect URI instead of defining your own in your app.

I recommend following the linked docs above to get through the GCP parts of this.

Creating login and sign up routes

To use Stytch (at least for Google OAuth) you need to create both a login and sign up route. Those routes are then added to your Redirect URLs dashboard. For testing purposes, these will be localhost. Note that the above link only works if you’ve already signed up for Stytch. You can use my code directly (utilizes flask so do be sure to install that into a venv).

from flask import Flask
from flask import request
from flask import render_template
from flask import session
app = Flask(__name__)
app.secret_key = "development"
@app.route("/login")
def login():
"""Login a user."""
if "token" in request.url:
access_token = request.args.get("token")
session["token"] = access_token # TOOD: move to a DB in production, and do something safer and scaleable 🙂
return render_template('login.html')
@app.route("/sign-up")
def sign_up():
"""Placeholder sign up route for interacting with Stytch API."""
return "PLACEHOLDER"
if __name__ == "__main__":
app.run(port=8080, debug=True)
view raw app.py hosted with ❤ by GitHub

We’re only going to be using the login route, but we need to have both routes defined as redirect URLs within Stytch.

Redirect URLs are defined in your dashboard

Go to your redirect URLs dashboard and add the two routes login and sign up.

Creating the button to redirect users to Stytch

Here’s some simple HTML code that renders a button. The magic here is the hyperlink in the anchor tag which redirects users to a Stytch URL that starts the Google OAuth process. You can find that OAuth Start URL by going to your Configuration then OAuth and clicking on Google Login under the displayed OAuth providers.

<html>
<head>
<style>
.container {
height: 200px;
position: relative;
}
.center {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
}
</style>
</head>
<body>
<div class="container">
<div class="center block">
<button>
<a href="https://test.stytch.com/v1/public/oauth/google/start?public_token=public-token-test-YOUR-TOKEN-HERE">Login</a>
</button>
</div>
</div>
</body>
</html>
view raw login.html hosted with ❤ by GitHub
The worlds most beautiful button

Once users click the button, they’ll get redirected to the typical Google sign-in screen. But afterwards, Stytch will forward you a token in a URL back to your /login route.

The login screen that Google displays to users for OAuth authentication

In our code we use the request.args object to get the corresponding token from the URL.

Authenticate the OAuth request

Once a user logs in Google redirects to Stytch (remember the redirect URI we defined in our OAuth credentials in the first step?), then Stytch redirects to us (our /login route) with the token as mentioned before. The final step is to authenticate that this user is indeed authenticated by hitting the Stytch authentication endpoint which for us is https://test.stytch.com/v1/oauth/authenticate. This endpoint verifies whether a user completed the OAuth flow and is still verified (e.g. a token hasn’t expired).

Important to note:

Stytch uses basic authentication which means you need to pass in username and password when authenticating a token (the username is your project_id and password is secret which are found in your API keys under the developer dashboard within Stytch).

Here’s a sample cURL snippet which you can model your own from.

curl --request POST --url https://test.stytch.com/v1/oauth/authenticate -u 'YOUR-PROJECT-NAME:YOUR-SECRET' -H 'Content-Type: application/json' -d '{ "token": "YOUR-TOKEN-FROM-LOGIN-REDIRECT" }'
view raw auth.txt hosted with ❤ by GitHub

If correctly authenticated you should receive a JSON response with a status code of 200.

And that’s it. Pretty cool service, I enjoyed learning more about them. Seems like they’ve got things like magic links and SMS one-time passwords too, excited to see what else they ship 🚢.!

Published by Paul Young-Suk Lee

SWE @lyft. Currently working on data infrastructure

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: