Using M2M to create API keys

Hi Stytch,

We use Stytch for consumer authentication today and we’re now about to add some public APIs to our platform. I had a few questions about your machine-to-machine product, and I’m curious if it’d be a good fit for our use case.

What we want to do is to issue non-expiring credentials to our users that they can use when making authenticated API calls. Our public API access will be tied to the same set of users we have in Stytch. We authenticate those users with email/password for auth and then issue our own session tokens.

Can we use M2M authentication to associate an API client with a single user?

Hey Alexander – thanks for posting!

I do think our M2M product could be a good fit for your use case. Here’s the flow I’m envisioning:

  1. A user signs into your application using your existing Stytch authentication flow.
  2. Once the user indicates that they’d like to call your public APIs (or upon new user signup), you’ll generate a new M2M client_id and secret for that particular user. You’ll display the client_id and secret to the user (while they’re logged into your application) for them to copy.
  3. The user will include their client_id and secret in calls that they make to your public APIs.
  4. Upon receiving an API call, you’ll call our Get access token endpoint with the user-provided client_id and secret, and then our Authenticate access token endpoint. Upon receiving a successful Authenticate access token response, you can proceed with the user’s API call.

In order to associate a given M2M client with a particular user, I’d recommend the following:

  1. When creating the M2M client, you’ll include the user’s Stytch user_id (or any other user data of your choice) in the client’s trusted_metadata object.
  2. You’ll create an M2M custom claims template that pulls the user data out of the client’s trusted_metadata object. For example, something like this, assuming you named the trusted_metadata field containing the user ID stytch_user_id:

{ "user_id": {{ client.trusted_metadata.stytch_user_id }}}

  1. The user_id value will be included in the custom_claims object of any Authenticate access token responses, so you’ll know which user made the API call.

Does the above strategy align with what you’re thinking?

Yes, thanks so much for the response, that helps clarify things a lot!

In this scenario, does the customer client have the permissions to create other m2m clients?