python-stytch-cerbos

An example application of integrating Cerbos with a FastAPI server using Stytch Magic Links for authentication.

Dependencies

Set up

  1. Retrieve the project ID and secret from here. Set the values to these env vars accordingly:

    STYTCH_PROJECT_ID
    STYTCH_SECRET
  2. Create Login and Sign-up redirect URLs as http://localhost:3000/callback, in the Redirect URLs page.

  3. Run docker-compose up -d to fire up the Cerbos PDP instance and the FastAPI server.

  4. Navigate to http://localhost:3000.

Run through

When loading up the app, you'll be greeted by the login page. You can specify a "role" there; either user or admin. This ultimately sends a followup request (after login/creation) to Stytch to update the trusted_metadata field of the user, via this API. This is retrieved on subsequent authentication checks to retrieve the user roles when verifying identity via this API.

Note: In production, you would handle the attribution of roles through some proper mechanism - the above is purely for demonstrative purposes.

Policies

This example has a simple CRUD policy in place for a resource kind of contact - like a CRM system would have. The policy file can be found in the cerbos/policies folder here.

Should you wish to experiment with this policy, you can try it in the Cerbos Playground.

The policy expects one of two roles to be set on the principal - admin and user. These roles are authorized as follows:

Action User Admin
list Y Y
read Y Y
create Y Y
update If owner Y
delete If owner Y